From 16db3732ba05f2a44d6ac37cad9b3d03d8efe0c3 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 23 Sep 2021 18:54:28 +0000 Subject: [PATCH 1/2] chore: use gapic-generator-python 0.51.2 fix: add 'dict' annotation type to 'request' Committer: @busunkim96 PiperOrigin-RevId: 398509016 Source-Link: https://github.com/googleapis/googleapis/commit/b224dfa52642a733ea64849d4e06d15c274bc08f Source-Link: https://github.com/googleapis/googleapis-gen/commit/63a1db7a38d74b9639592f521ed1daaf7299ad9a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjNhMWRiN2EzOGQ3NGI5NjM5NTkyZjUyMWVkMWRhYWY3Mjk5YWQ5YSJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../docs/websecurityscanner_v1/services.rst | 6 + .../v1/docs/websecurityscanner_v1/types.rst | 7 + .../web_security_scanner.rst | 10 + .../cloud/websecurityscanner/__init__.py | 87 + .../google/cloud/websecurityscanner/py.typed | 2 + .../cloud/websecurityscanner_v1/__init__.py | 88 + .../websecurityscanner_v1/gapic_metadata.json | 153 + .../cloud/websecurityscanner_v1/py.typed | 2 + .../services/__init__.py | 15 + .../services/web_security_scanner/__init__.py | 22 + .../web_security_scanner/async_client.py | 992 ++++ .../services/web_security_scanner/client.py | 1133 ++++ .../services/web_security_scanner/pagers.py | 510 ++ .../transports/__init__.py | 33 + .../web_security_scanner/transports/base.py | 403 ++ .../web_security_scanner/transports/grpc.py | 574 ++ .../transports/grpc_asyncio.py | 578 ++ .../websecurityscanner_v1/types/__init__.py | 102 + .../types/crawled_url.py | 58 + .../websecurityscanner_v1/types/finding.py | 185 + .../types/finding_addon.py | 206 + .../types/finding_type_stats.py | 50 + .../types/scan_config.py | 299 + .../types/scan_config_error.py | 103 + .../websecurityscanner_v1/types/scan_run.py | 151 + .../types/scan_run_error_trace.py | 76 + .../types/scan_run_warning_trace.py | 55 + .../types/web_security_scanner.py | 462 ++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../fixup_websecurityscanner_v1_keywords.py | 188 + owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/websecurityscanner_v1/__init__.py | 16 + .../test_web_security_scanner.py | 3877 +++++++++++++ owl-bot-staging/v1alpha/.coveragerc | 17 + owl-bot-staging/v1alpha/MANIFEST.in | 2 + owl-bot-staging/v1alpha/README.rst | 49 + owl-bot-staging/v1alpha/docs/conf.py | 376 ++ owl-bot-staging/v1alpha/docs/index.rst | 7 + .../websecurityscanner_v1alpha/services.rst | 6 + .../docs/websecurityscanner_v1alpha/types.rst | 7 + .../web_security_scanner.rst | 10 + .../cloud/websecurityscanner/__init__.py | 79 + .../google/cloud/websecurityscanner/py.typed | 2 + .../websecurityscanner_v1alpha/__init__.py | 80 + .../gapic_metadata.json | 153 + .../cloud/websecurityscanner_v1alpha/py.typed | 2 + .../services/__init__.py | 15 + .../services/web_security_scanner/__init__.py | 22 + .../web_security_scanner/async_client.py | 1314 +++++ .../services/web_security_scanner/client.py | 1460 +++++ .../services/web_security_scanner/pagers.py | 510 ++ .../transports/__init__.py | 33 + .../web_security_scanner/transports/base.py | 404 ++ .../web_security_scanner/transports/grpc.py | 575 ++ .../transports/grpc_asyncio.py | 579 ++ .../types/__init__.py | 88 + .../types/crawled_url.py | 58 + .../types/finding.py | 168 + .../types/finding_addon.py | 151 + .../types/finding_type_stats.py | 52 + .../types/scan_config.py | 229 + .../types/scan_run.py | 129 + .../types/web_security_scanner.py | 463 ++ owl-bot-staging/v1alpha/mypy.ini | 3 + owl-bot-staging/v1alpha/noxfile.py | 132 + ...xup_websecurityscanner_v1alpha_keywords.py | 188 + owl-bot-staging/v1alpha/setup.py | 54 + owl-bot-staging/v1alpha/tests/__init__.py | 16 + .../v1alpha/tests/unit/__init__.py | 16 + .../v1alpha/tests/unit/gapic/__init__.py | 16 + .../websecurityscanner_v1alpha/__init__.py | 16 + .../test_web_security_scanner.py | 4934 ++++++++++++++++ owl-bot-staging/v1beta/.coveragerc | 17 + owl-bot-staging/v1beta/MANIFEST.in | 2 + owl-bot-staging/v1beta/README.rst | 49 + owl-bot-staging/v1beta/docs/conf.py | 376 ++ owl-bot-staging/v1beta/docs/index.rst | 7 + .../websecurityscanner_v1beta/services.rst | 6 + .../docs/websecurityscanner_v1beta/types.rst | 7 + .../web_security_scanner.rst | 10 + .../cloud/websecurityscanner/__init__.py | 87 + .../google/cloud/websecurityscanner/py.typed | 2 + .../websecurityscanner_v1beta/__init__.py | 88 + .../gapic_metadata.json | 153 + .../cloud/websecurityscanner_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/web_security_scanner/__init__.py | 22 + .../web_security_scanner/async_client.py | 1316 +++++ .../services/web_security_scanner/client.py | 1462 +++++ .../services/web_security_scanner/pagers.py | 510 ++ .../transports/__init__.py | 33 + .../web_security_scanner/transports/base.py | 404 ++ .../web_security_scanner/transports/grpc.py | 575 ++ .../transports/grpc_asyncio.py | 579 ++ .../types/__init__.py | 102 + .../types/crawled_url.py | 58 + .../types/finding.py | 165 + .../types/finding_addon.py | 173 + .../types/finding_type_stats.py | 49 + .../types/scan_config.py | 262 + .../types/scan_config_error.py | 103 + .../types/scan_run.py | 148 + .../types/scan_run_error_trace.py | 75 + .../types/scan_run_warning_trace.py | 55 + .../types/web_security_scanner.py | 463 ++ owl-bot-staging/v1beta/mypy.ini | 3 + owl-bot-staging/v1beta/noxfile.py | 132 + ...ixup_websecurityscanner_v1beta_keywords.py | 188 + owl-bot-staging/v1beta/setup.py | 54 + owl-bot-staging/v1beta/tests/__init__.py | 16 + owl-bot-staging/v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../websecurityscanner_v1beta/__init__.py | 16 + .../test_web_security_scanner.py | 4961 +++++++++++++++++ 123 files changed, 36323 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py create mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py create mode 100644 owl-bot-staging/v1alpha/.coveragerc create mode 100644 owl-bot-staging/v1alpha/MANIFEST.in create mode 100644 owl-bot-staging/v1alpha/README.rst create mode 100644 owl-bot-staging/v1alpha/docs/conf.py create mode 100644 owl-bot-staging/v1alpha/docs/index.rst create mode 100644 owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst create mode 100644 owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst create mode 100644 owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py create mode 100644 owl-bot-staging/v1alpha/mypy.ini create mode 100644 owl-bot-staging/v1alpha/noxfile.py create mode 100644 owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py create mode 100644 owl-bot-staging/v1alpha/setup.py create mode 100644 owl-bot-staging/v1alpha/tests/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py create mode 100644 owl-bot-staging/v1beta/.coveragerc create mode 100644 owl-bot-staging/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/v1beta/README.rst create mode 100644 owl-bot-staging/v1beta/docs/conf.py create mode 100644 owl-bot-staging/v1beta/docs/index.rst create mode 100644 owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst create mode 100644 owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst create mode 100644 owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py create mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py create mode 100644 owl-bot-staging/v1beta/mypy.ini create mode 100644 owl-bot-staging/v1beta/noxfile.py create mode 100644 owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py create mode 100644 owl-bot-staging/v1beta/setup.py create mode 100644 owl-bot-staging/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py create mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..6b433c1 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/websecurityscanner/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..9d26e3b --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/websecurityscanner *.py +recursive-include google/cloud/websecurityscanner_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..4de4c10 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Websecurityscanner API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Websecurityscanner API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..c393cbd --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-websecurityscanner documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-websecurityscanner" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-websecurityscanner-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-websecurityscanner.tex", + u"google-cloud-websecurityscanner Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-websecurityscanner", + u"Google Cloud Websecurityscanner Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-websecurityscanner", + u"google-cloud-websecurityscanner Documentation", + author, + "google-cloud-websecurityscanner", + "GAPIC library for Google Cloud Websecurityscanner API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..f8b680d --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + websecurityscanner_v1/services + websecurityscanner_v1/types diff --git a/owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst b/owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst new file mode 100644 index 0000000..6fb98e6 --- /dev/null +++ b/owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Websecurityscanner v1 API +=================================================== +.. toctree:: + :maxdepth: 2 + + web_security_scanner diff --git a/owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst b/owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst new file mode 100644 index 0000000..aadd787 --- /dev/null +++ b/owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Websecurityscanner v1 API +================================================ + +.. automodule:: google.cloud.websecurityscanner_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst b/owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst new file mode 100644 index 0000000..4925421 --- /dev/null +++ b/owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst @@ -0,0 +1,10 @@ +WebSecurityScanner +------------------------------------ + +.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner + :members: + :inherited-members: + +.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py new file mode 100644 index 0000000..e83d0b5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1.services.web_security_scanner.client import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient + +from google.cloud.websecurityscanner_v1.types.crawled_url import CrawledUrl +from google.cloud.websecurityscanner_v1.types.finding import Finding +from google.cloud.websecurityscanner_v1.types.finding_addon import Form +from google.cloud.websecurityscanner_v1.types.finding_addon import OutdatedLibrary +from google.cloud.websecurityscanner_v1.types.finding_addon import ViolatingResource +from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableHeaders +from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableParameters +from google.cloud.websecurityscanner_v1.types.finding_addon import Xss +from google.cloud.websecurityscanner_v1.types.finding_type_stats import FindingTypeStats +from google.cloud.websecurityscanner_v1.types.scan_config import ScanConfig +from google.cloud.websecurityscanner_v1.types.scan_config_error import ScanConfigError +from google.cloud.websecurityscanner_v1.types.scan_run import ScanRun +from google.cloud.websecurityscanner_v1.types.scan_run_error_trace import ScanRunErrorTrace +from google.cloud.websecurityscanner_v1.types.scan_run_warning_trace import ScanRunWarningTrace +from google.cloud.websecurityscanner_v1.types.web_security_scanner import CreateScanConfigRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import DeleteScanConfigRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetFindingRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanConfigRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanRunRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsResponse +from google.cloud.websecurityscanner_v1.types.web_security_scanner import StartScanRunRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import StopScanRunRequest +from google.cloud.websecurityscanner_v1.types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ('WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed new file mode 100644 index 0000000..8cfb5d2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py new file mode 100644 index 0000000..130eb6c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.web_security_scanner import WebSecurityScannerClient +from .services.web_security_scanner import WebSecurityScannerAsyncClient + +from .types.crawled_url import CrawledUrl +from .types.finding import Finding +from .types.finding_addon import Form +from .types.finding_addon import OutdatedLibrary +from .types.finding_addon import ViolatingResource +from .types.finding_addon import VulnerableHeaders +from .types.finding_addon import VulnerableParameters +from .types.finding_addon import Xss +from .types.finding_type_stats import FindingTypeStats +from .types.scan_config import ScanConfig +from .types.scan_config_error import ScanConfigError +from .types.scan_run import ScanRun +from .types.scan_run_error_trace import ScanRunErrorTrace +from .types.scan_run_warning_trace import ScanRunWarningTrace +from .types.web_security_scanner import CreateScanConfigRequest +from .types.web_security_scanner import DeleteScanConfigRequest +from .types.web_security_scanner import GetFindingRequest +from .types.web_security_scanner import GetScanConfigRequest +from .types.web_security_scanner import GetScanRunRequest +from .types.web_security_scanner import ListCrawledUrlsRequest +from .types.web_security_scanner import ListCrawledUrlsResponse +from .types.web_security_scanner import ListFindingsRequest +from .types.web_security_scanner import ListFindingsResponse +from .types.web_security_scanner import ListFindingTypeStatsRequest +from .types.web_security_scanner import ListFindingTypeStatsResponse +from .types.web_security_scanner import ListScanConfigsRequest +from .types.web_security_scanner import ListScanConfigsResponse +from .types.web_security_scanner import ListScanRunsRequest +from .types.web_security_scanner import ListScanRunsResponse +from .types.web_security_scanner import StartScanRunRequest +from .types.web_security_scanner import StopScanRunRequest +from .types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ( + 'WebSecurityScannerAsyncClient', +'CrawledUrl', +'CreateScanConfigRequest', +'DeleteScanConfigRequest', +'Finding', +'FindingTypeStats', +'Form', +'GetFindingRequest', +'GetScanConfigRequest', +'GetScanRunRequest', +'ListCrawledUrlsRequest', +'ListCrawledUrlsResponse', +'ListFindingTypeStatsRequest', +'ListFindingTypeStatsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListScanConfigsRequest', +'ListScanConfigsResponse', +'ListScanRunsRequest', +'ListScanRunsResponse', +'OutdatedLibrary', +'ScanConfig', +'ScanConfigError', +'ScanRun', +'ScanRunErrorTrace', +'ScanRunWarningTrace', +'StartScanRunRequest', +'StopScanRunRequest', +'UpdateScanConfigRequest', +'ViolatingResource', +'VulnerableHeaders', +'VulnerableParameters', +'WebSecurityScannerClient', +'Xss', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json new file mode 100644 index 0000000..2b6f23a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json @@ -0,0 +1,153 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.websecurityscanner_v1", + "protoPackage": "google.cloud.websecurityscanner.v1", + "schema": "1.0", + "services": { + "WebSecurityScanner": { + "clients": { + "grpc": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebSecurityScannerAsyncClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed new file mode 100644 index 0000000..8cfb5d2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py new file mode 100644 index 0000000..46b053b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import WebSecurityScannerClient +from .async_client import WebSecurityScannerAsyncClient + +__all__ = ( + 'WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py new file mode 100644 index 0000000..c5873e0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py @@ -0,0 +1,992 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_addon +from google.cloud.websecurityscanner_v1.types import finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .client import WebSecurityScannerClient + + +class WebSecurityScannerAsyncClient: + """Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + """ + + _client: WebSecurityScannerClient + + DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + + finding_path = staticmethod(WebSecurityScannerClient.finding_path) + parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) + common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) + parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) + common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) + parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) + common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) + parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) + common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) + parse_common_location_path = staticmethod(WebSecurityScannerClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WebSecurityScannerClient).get_transport_class, type(WebSecurityScannerClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, WebSecurityScannerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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, ~.WebSecurityScannerTransport]): 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 = WebSecurityScannerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_scan_config(self, + request: web_security_scanner.CreateScanConfigRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest`): + The request object. Request for the `CreateScanConfig` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.CreateScanConfigRequest(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.create_scan_config, + default_timeout=600.0, + client_info=DEFAULT_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_scan_config(self, + request: web_security_scanner.DeleteScanConfigRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest`): + The request object. Request for the `DeleteScanConfig` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.DeleteScanConfigRequest(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.delete_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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_scan_config(self, + request: web_security_scanner.GetScanConfigRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.GetScanConfigRequest`): + The request object. Request for the `GetScanConfig` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.GetScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_scan_configs(self, + request: web_security_scanner.ListScanConfigsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsAsyncPager: + r"""Lists ScanConfigs under a given project. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest`): + The request object. Request for the `ListScanConfigs` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: + Response for the ListScanConfigs method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListScanConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scan_config(self, + request: web_security_scanner.UpdateScanConfigRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest`): + The request object. Request for the + `UpdateScanConfigRequest` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.UpdateScanConfigRequest(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.update_scan_config, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def start_scan_run(self, + request: web_security_scanner.StartScanRunRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.StartScanRunRequest`): + The request object. Request for the `StartScanRun` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.StartScanRunRequest(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.start_scan_run, + default_timeout=600.0, + client_info=DEFAULT_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_scan_run(self, + request: web_security_scanner.GetScanRunRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.GetScanRunRequest`): + The request object. Request for the `GetScanRun` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.GetScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_scan_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_scan_runs(self, + request: web_security_scanner.ListScanRunsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsAsyncPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.ListScanRunsRequest`): + The request object. Request for the `ListScanRuns` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsAsyncPager: + Response for the ListScanRuns method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.ListScanRunsRequest(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_scan_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListScanRunsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_scan_run(self, + request: web_security_scanner.StopScanRunRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.StopScanRunRequest`): + The request object. Request for the `StopScanRun` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.StopScanRunRequest(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.stop_scan_run, + default_timeout=600.0, + client_info=DEFAULT_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 list_crawled_urls(self, + request: web_security_scanner.ListCrawledUrlsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsAsyncPager: + r"""List CrawledUrls under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest`): + The request object. Request for the `ListCrawledUrls` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: + Response for the ListCrawledUrls method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListCrawledUrlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_finding(self, + request: web_security_scanner.GetFindingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.GetFindingRequest`): + The request object. Request for the `GetFinding` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.GetFindingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_finding, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_findings(self, + request: web_security_scanner.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""List Findings under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.ListFindingsRequest`): + The request object. Request for the `ListFindings` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsAsyncPager: + Response for the ListFindings method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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_finding_type_stats(self, + request: web_security_scanner.ListFindingTypeStatsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest`): + The request object. Request for the + `ListFindingTypeStats` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # Create or coerce a protobuf request object. + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-websecurityscanner", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebSecurityScannerAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py new file mode 100644 index 0000000..f43e67b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py @@ -0,0 +1,1133 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_addon +from google.cloud.websecurityscanner_v1.types import finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebSecurityScannerGrpcTransport +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport + + +class WebSecurityScannerClientMeta(type): + """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] + _transport_registry["grpc"] = WebSecurityScannerGrpcTransport + _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[WebSecurityScannerTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): + """Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "websecurityscanner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, WebSecurityScannerTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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, WebSecurityScannerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, WebSecurityScannerTransport): + # transport is a WebSecurityScannerTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_scan_config(self, + request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]): + The request object. Request for the `CreateScanConfig` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.CreateScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scan_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_scan_config(self, + request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]): + The request object. Request for the `DeleteScanConfig` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.DeleteScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_scan_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_scan_config(self, + request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]): + The request object. Request for the `GetScanConfig` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.GetScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_scan_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 list_scan_configs(self, + request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsPager: + r"""Lists ScanConfigs under a given project. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]): + The request object. Request for the `ListScanConfigs` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsPager: + Response for the ListScanConfigs method. + + 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 web_security_scanner.ListScanConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_scan_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.ListScanConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scan_config(self, + request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]): + The request object. Request for the + `UpdateScanConfigRequest` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.UpdateScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def start_scan_run(self, + request: Union[web_security_scanner.StartScanRunRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]): + The request object. Request for the `StartScanRun` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.StartScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_scan_run] + + # 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_scan_run(self, + request: Union[web_security_scanner.GetScanRunRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]): + The request object. Request for the `GetScanRun` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.GetScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_scan_run] + + # 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 list_scan_runs(self, + request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]): + The request object. Request for the `ListScanRuns` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsPager: + Response for the ListScanRuns method. + + 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 web_security_scanner.ListScanRunsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_scan_runs] + + # 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.ListScanRunsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_scan_run(self, + request: Union[web_security_scanner.StopScanRunRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]): + The request object. Request for the `StopScanRun` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.StopScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_scan_run] + + # 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 list_crawled_urls(self, + request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsPager: + r"""List CrawledUrls under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]): + The request object. Request for the `ListCrawledUrls` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsPager: + Response for the ListCrawledUrls method. + + 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 web_security_scanner.ListCrawledUrlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_crawled_urls] + + # 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.ListCrawledUrlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_finding(self, + request: Union[web_security_scanner.GetFindingRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]): + The request object. Request for the `GetFinding` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.GetFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_finding] + + # 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 list_findings(self, + request: Union[web_security_scanner.ListFindingsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""List Findings under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]): + The request object. Request for the `ListFindings` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsPager: + Response for the ListFindings method. + + 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 web_security_scanner.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.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_finding_type_stats(self, + request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]): + The request object. Request for the + `ListFindingTypeStats` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a web_security_scanner.ListFindingTypeStatsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_finding_type_stats] + + # 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-websecurityscanner", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebSecurityScannerClient", +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py new file mode 100644 index 0000000..e7efdf9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner + + +class ListScanConfigsPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` + 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[..., web_security_scanner.ListScanConfigsResponse], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): + 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 = web_security_scanner.ListScanConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + for page in self.pages: + yield from page.scan_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanConfigsAsyncPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` + 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[web_security_scanner.ListScanConfigsResponse]], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): + 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 = web_security_scanner.ListScanConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` + 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[..., web_security_scanner.ListScanRunsResponse], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): + 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 = web_security_scanner.ListScanRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + for page in self.pages: + yield from page.scan_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsAsyncPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` + 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[web_security_scanner.ListScanRunsResponse]], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): + 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 = web_security_scanner.ListScanRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` + 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[..., web_security_scanner.ListCrawledUrlsResponse], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): + 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 = web_security_scanner.ListCrawledUrlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + for page in self.pages: + yield from page.crawled_urls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsAsyncPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` + 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[web_security_scanner.ListCrawledUrlsResponse]], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): + 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 = web_security_scanner.ListCrawledUrlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + async def async_generator(): + async for page in self.pages: + for response in page.crawled_urls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListFindingsResponse], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[web_security_scanner.ListFindingsResponse]], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.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[web_security_scanner.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) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py new file mode 100644 index 0000000..19f4df5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import WebSecurityScannerTransport +from .grpc import WebSecurityScannerGrpcTransport +from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] +_transport_registry['grpc'] = WebSecurityScannerGrpcTransport +_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport + +__all__ = ( + 'WebSecurityScannerTransport', + 'WebSecurityScannerGrpcTransport', + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py new file mode 100644 index 0000000..9ac4b7b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py @@ -0,0 +1,403 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-websecurityscanner', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class WebSecurityScannerTransport(abc.ABC): + """Abstract transport class for WebSecurityScanner.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'websecurityscanner.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_scan_config: gapic_v1.method.wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: gapic_v1.method.wrap_method( + self.delete_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: gapic_v1.method.wrap_method( + self.get_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: gapic_v1.method.wrap_method( + self.list_scan_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: gapic_v1.method.wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: gapic_v1.method.wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: gapic_v1.method.wrap_method( + self.get_scan_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: gapic_v1.method.wrap_method( + self.list_scan_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: gapic_v1.method.wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: gapic_v1.method.wrap_method( + self.list_crawled_urls, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: gapic_v1.method.wrap_method( + self.get_finding, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: gapic_v1.method.wrap_method( + self.list_finding_type_stats, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Union[ + web_security_scanner.ListScanConfigsResponse, + Awaitable[web_security_scanner.ListScanConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Union[ + web_security_scanner.ListScanRunsResponse, + Awaitable[web_security_scanner.ListScanRunsResponse] + ]]: + raise NotImplementedError() + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Union[ + web_security_scanner.ListCrawledUrlsResponse, + Awaitable[web_security_scanner.ListCrawledUrlsResponse] + ]]: + raise NotImplementedError() + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Union[ + web_security_scanner.ListFindingsResponse, + Awaitable[web_security_scanner.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Union[ + web_security_scanner.ListFindingTypeStatsResponse, + Awaitable[web_security_scanner.ListFindingTypeStatsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'WebSecurityScannerTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py new file mode 100644 index 0000000..b338a65 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + + +class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): + """gRPC backend transport for WebSecurityScanner. + + Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + + 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 = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + ~.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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + ~.ListScanConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + ~.ListScanRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + ~.ListCrawledUrlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + ~.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 'get_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + 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.websecurityscanner.v1.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + ~.ListFindingTypeStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + +__all__ = ( + 'WebSecurityScannerGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py new file mode 100644 index 0000000..7062170 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py @@ -0,0 +1,578 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .grpc import WebSecurityScannerGrpcTransport + + +class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): + """gRPC AsyncIO backend transport for WebSecurityScanner. + + Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + + 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 = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + 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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Awaitable[web_security_scanner.ListScanConfigsResponse]]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + Awaitable[~.ListScanConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Awaitable[web_security_scanner.ListScanRunsResponse]]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + Awaitable[~.ListScanRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + Awaitable[~.ListCrawledUrlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + 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 'get_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Awaitable[web_security_scanner.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + 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.websecurityscanner.v1.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + Awaitable[~.ListFindingTypeStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + +__all__ = ( + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py new file mode 100644 index 0000000..36cb2b7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .crawled_url import ( + CrawledUrl, +) +from .finding import ( + Finding, +) +from .finding_addon import ( + Form, + OutdatedLibrary, + ViolatingResource, + VulnerableHeaders, + VulnerableParameters, + Xss, +) +from .finding_type_stats import ( + FindingTypeStats, +) +from .scan_config import ( + ScanConfig, +) +from .scan_config_error import ( + ScanConfigError, +) +from .scan_run import ( + ScanRun, +) +from .scan_run_error_trace import ( + ScanRunErrorTrace, +) +from .scan_run_warning_trace import ( + ScanRunWarningTrace, +) +from .web_security_scanner import ( + CreateScanConfigRequest, + DeleteScanConfigRequest, + GetFindingRequest, + GetScanConfigRequest, + GetScanRunRequest, + ListCrawledUrlsRequest, + ListCrawledUrlsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListFindingTypeStatsRequest, + ListFindingTypeStatsResponse, + ListScanConfigsRequest, + ListScanConfigsResponse, + ListScanRunsRequest, + ListScanRunsResponse, + StartScanRunRequest, + StopScanRunRequest, + UpdateScanConfigRequest, +) + +__all__ = ( + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py new file mode 100644 index 0000000..42e6c94 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1', + manifest={ + 'CrawledUrl', + }, +) + + +class CrawledUrl(proto.Message): + r"""A CrawledUrl resource represents a URL that was crawled + during a ScanRun. Web Security Scanner Service crawls the web + applications, following all links within the scope of sites, to + find the URLs to test against. + + Attributes: + http_method (str): + Output only. The http method of the request + that was used to visit the URL, in uppercase. + url (str): + Output only. The URL that was crawled. + body (str): + Output only. The body of the request that was + used to visit the URL. + """ + + http_method = proto.Field( + proto.STRING, + number=1, + ) + url = proto.Field( + proto.STRING, + number=2, + ) + body = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py new file mode 100644 index 0000000..12855fc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1.types import finding_addon + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""A Finding resource represents a vulnerability instance + identified during a ScanRun. + + Attributes: + name (str): + Output only. The resource name of the + Finding. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. + The finding IDs are generated by the system. + finding_type (str): + Output only. The type of the Finding. + Detailed and up-to-date information on findings + can be found here: + https://cloud.google.com/security-command- + center/docs/how-to-remediate-web-security- + scanner-findings + severity (google.cloud.websecurityscanner_v1.types.Finding.Severity): + Output only. The severity level of the + reported vulnerability. + http_method (str): + Output only. The http method of the request + that triggered the vulnerability, in uppercase. + fuzzed_url (str): + Output only. The URL produced by the server- + ide fuzzer and used in the request that + triggered the vulnerability. + body (str): + Output only. The body of the request that + triggered the vulnerability. + description (str): + Output only. The description of the + vulnerability. + reproduction_url (str): + Output only. The URL containing human- + eadable payload that user can leverage to + reproduce the vulnerability. + frame_url (str): + Output only. If the vulnerability was + originated from nested IFrame, the immediate + parent IFrame is reported. + final_url (str): + Output only. The URL where the browser lands + when the vulnerability is detected. + tracking_id (str): + Output only. The tracking ID uniquely + identifies a vulnerability instance across + multiple ScanRuns. + form (google.cloud.websecurityscanner_v1.types.Form): + Output only. An addon containing information + reported for a vulnerability with an HTML form, + if any. + outdated_library (google.cloud.websecurityscanner_v1.types.OutdatedLibrary): + Output only. An addon containing information + about outdated libraries. + violating_resource (google.cloud.websecurityscanner_v1.types.ViolatingResource): + Output only. An addon containing detailed + information regarding any resource causing the + vulnerability such as JavaScript sources, image, + audio files, etc. + vulnerable_headers (google.cloud.websecurityscanner_v1.types.VulnerableHeaders): + Output only. An addon containing information + about vulnerable or missing HTTP headers. + vulnerable_parameters (google.cloud.websecurityscanner_v1.types.VulnerableParameters): + Output only. An addon containing information + about request parameters which were found to be + vulnerable. + xss (google.cloud.websecurityscanner_v1.types.Xss): + Output only. An addon containing information + reported for an XSS, if any. + """ + class Severity(proto.Enum): + r"""The severity level of a vulnerability.""" + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + finding_type = proto.Field( + proto.STRING, + number=2, + ) + severity = proto.Field( + proto.ENUM, + number=17, + enum=Severity, + ) + http_method = proto.Field( + proto.STRING, + number=3, + ) + fuzzed_url = proto.Field( + proto.STRING, + number=4, + ) + body = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + reproduction_url = proto.Field( + proto.STRING, + number=7, + ) + frame_url = proto.Field( + proto.STRING, + number=8, + ) + final_url = proto.Field( + proto.STRING, + number=9, + ) + tracking_id = proto.Field( + proto.STRING, + number=10, + ) + form = proto.Field( + proto.MESSAGE, + number=16, + message=finding_addon.Form, + ) + outdated_library = proto.Field( + proto.MESSAGE, + number=11, + message=finding_addon.OutdatedLibrary, + ) + violating_resource = proto.Field( + proto.MESSAGE, + number=12, + message=finding_addon.ViolatingResource, + ) + vulnerable_headers = proto.Field( + proto.MESSAGE, + number=15, + message=finding_addon.VulnerableHeaders, + ) + vulnerable_parameters = proto.Field( + proto.MESSAGE, + number=13, + message=finding_addon.VulnerableParameters, + ) + xss = proto.Field( + proto.MESSAGE, + number=14, + message=finding_addon.Xss, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py new file mode 100644 index 0000000..2be0c61 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1', + manifest={ + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableParameters', + 'VulnerableHeaders', + 'Xss', + }, +) + + +class Form(proto.Message): + r"""! Information about a vulnerability with an HTML. + Attributes: + action_uri (str): + ! The URI where to send the form when it's + submitted. + fields (Sequence[str]): + ! The names of form fields related to the + vulnerability. + """ + + action_uri = proto.Field( + proto.STRING, + number=1, + ) + fields = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class OutdatedLibrary(proto.Message): + r"""Information reported for an outdated library. + Attributes: + library_name (str): + The name of the outdated library. + version (str): + The version number. + learn_more_urls (Sequence[str]): + URLs to learn more information about the + vulnerabilities in the library. + """ + + library_name = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + learn_more_urls = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ViolatingResource(proto.Message): + r"""Information regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, etc. + + Attributes: + content_type (str): + The MIME type of this resource. + resource_url (str): + URL of this violating resource. + """ + + content_type = proto.Field( + proto.STRING, + number=1, + ) + resource_url = proto.Field( + proto.STRING, + number=2, + ) + + +class VulnerableParameters(proto.Message): + r"""Information about vulnerable request parameters. + Attributes: + parameter_names (Sequence[str]): + The vulnerable parameter names. + """ + + parameter_names = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VulnerableHeaders(proto.Message): + r"""Information about vulnerable or missing HTTP Headers. + Attributes: + headers (Sequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): + List of vulnerable headers. + missing_headers (Sequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): + List of missing headers. + """ + + class Header(proto.Message): + r"""Describes a HTTP Header. + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.STRING, + number=2, + ) + + headers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Header, + ) + missing_headers = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Header, + ) + + +class Xss(proto.Message): + r"""Information reported for an XSS. + Attributes: + stack_traces (Sequence[str]): + Stack traces leading to the point where the + XSS occurred. + error_message (str): + An error message generated by a javascript + breakage. + attack_vector (google.cloud.websecurityscanner_v1.types.Xss.AttackVector): + The attack vector of the payload triggering + this XSS. + stored_xss_seeding_url (str): + The reproduction url for the seeding POST + request of a Stored XSS. + """ + class AttackVector(proto.Enum): + r"""Types of XSS attack vector.""" + ATTACK_VECTOR_UNSPECIFIED = 0 + LOCAL_STORAGE = 1 + SESSION_STORAGE = 2 + WINDOW_NAME = 3 + REFERRER = 4 + FORM_INPUT = 5 + COOKIE = 6 + POST_MESSAGE = 7 + GET_PARAMETERS = 8 + URL_FRAGMENT = 9 + HTML_COMMENT = 10 + POST_PARAMETERS = 11 + PROTOCOL = 12 + STORED_XSS = 13 + SAME_ORIGIN = 14 + USER_CONTROLLABLE_URL = 15 + + stack_traces = proto.RepeatedField( + proto.STRING, + number=1, + ) + error_message = proto.Field( + proto.STRING, + number=2, + ) + attack_vector = proto.Field( + proto.ENUM, + number=3, + enum=AttackVector, + ) + stored_xss_seeding_url = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py new file mode 100644 index 0000000..2af70e9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'FindingTypeStats', + }, +) + + +class FindingTypeStats(proto.Message): + r"""A FindingTypeStats resource represents stats regarding a + specific FindingType of Findings under a given ScanRun. + + Attributes: + finding_type (str): + Output only. The finding type associated with + the stats. + finding_count (int): + Output only. The count of findings belonging + to this finding type. + """ + + finding_type = proto.Field( + proto.STRING, + number=1, + ) + finding_count = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py new file mode 100644 index 0000000..e906d2f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanConfig', + }, +) + + +class ScanConfig(proto.Message): + r"""A ScanConfig resource contains the configurations to launch a + scan. + + Attributes: + name (str): + The resource name of the ScanConfig. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + The ScanConfig IDs are generated by the system. + display_name (str): + Required. The user provided display name of + the ScanConfig. + max_qps (int): + The maximum QPS during scanning. A valid value ranges from 5 + to 20 inclusively. If the field is unspecified or its value + is set 0, server will default to 15. Other values outside of + [5, 20] range will be rejected with INVALID_ARGUMENT error. + starting_urls (Sequence[str]): + Required. The starting URLs from which the + scanner finds site pages. + authentication (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication): + The authentication configuration. If + specified, service will use the authentication + configuration during scanning. + user_agent (google.cloud.websecurityscanner_v1.types.ScanConfig.UserAgent): + The user agent used during scanning. + blacklist_patterns (Sequence[str]): + The excluded URL patterns as described in + https://cloud.google.com/security-command-center/docs/how-to-use-web-security-scanner#excluding_urls + schedule (google.cloud.websecurityscanner_v1.types.ScanConfig.Schedule): + The schedule of the ScanConfig. + export_to_security_command_center (google.cloud.websecurityscanner_v1.types.ScanConfig.ExportToSecurityCommandCenter): + Controls export of scan configurations and + results to Security Command Center. + risk_level (google.cloud.websecurityscanner_v1.types.ScanConfig.RiskLevel): + The risk level selected for the scan + managed_scan (bool): + Whether the scan config is managed by Web + Security Scanner, output only. + static_ip_scan (bool): + Whether the scan configuration has enabled + static IP address scan feature. If enabled, the + scanner will access applications from static IP + addresses. + """ + class UserAgent(proto.Enum): + r"""Type of user agents used for scanning.""" + USER_AGENT_UNSPECIFIED = 0 + CHROME_LINUX = 1 + CHROME_ANDROID = 2 + SAFARI_IPHONE = 3 + + class RiskLevel(proto.Enum): + r"""Scan risk levels supported by Web Security Scanner. LOW + impact scanning will minimize requests with the potential to + modify data. To achieve the maximum scan coverage, NORMAL risk + level is recommended. + """ + RISK_LEVEL_UNSPECIFIED = 0 + NORMAL = 1 + LOW = 2 + + class ExportToSecurityCommandCenter(proto.Enum): + r"""Controls export of scan configurations and results to + Security Command Center. + """ + EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + class Authentication(proto.Message): + r"""Scan authentication configuration. + Attributes: + google_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.GoogleAccount): + Authentication using a Google account. + custom_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.CustomAccount): + Authentication using a custom account. + iap_credential (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential): + Authentication using Identity-Aware-Proxy + (IAP). + """ + + class GoogleAccount(proto.Message): + r"""Describes authentication configuration that uses a Google + account. + + Attributes: + username (str): + Required. The user name of the Google + account. + password (str): + Required. Input only. The password of the + Google account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + """ + + username = proto.Field( + proto.STRING, + number=1, + ) + password = proto.Field( + proto.STRING, + number=2, + ) + + class CustomAccount(proto.Message): + r"""Describes authentication configuration that uses a custom + account. + + Attributes: + username (str): + Required. The user name of the custom + account. + password (str): + Required. Input only. The password of the + custom account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + login_url (str): + Required. The login form URL of the website. + """ + + username = proto.Field( + proto.STRING, + number=1, + ) + password = proto.Field( + proto.STRING, + number=2, + ) + login_url = proto.Field( + proto.STRING, + number=3, + ) + + class IapCredential(proto.Message): + r"""Describes authentication configuration for Identity-Aware- + roxy (IAP). + + Attributes: + iap_test_service_account_info (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo): + Authentication configuration when Web- + ecurity-Scanner service account is added in + Identity-Aware-Proxy (IAP) access policies. + """ + + class IapTestServiceAccountInfo(proto.Message): + r"""Describes authentication configuration when Web-Security- + canner service account is added in Identity-Aware-Proxy (IAP) + access policies. + + Attributes: + target_audience_client_id (str): + Required. Describes OAuth2 client id of + resources protected by Identity-Aware-Proxy + (IAP). + """ + + target_audience_client_id = proto.Field( + proto.STRING, + number=1, + ) + + iap_test_service_account_info = proto.Field( + proto.MESSAGE, + number=1, + oneof='iap_credentials', + message='ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo', + ) + + google_account = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication', + message='ScanConfig.Authentication.GoogleAccount', + ) + custom_account = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication', + message='ScanConfig.Authentication.CustomAccount', + ) + iap_credential = proto.Field( + proto.MESSAGE, + number=4, + oneof='authentication', + message='ScanConfig.Authentication.IapCredential', + ) + + class Schedule(proto.Message): + r"""Scan schedule configuration. + Attributes: + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + A timestamp indicates when the next run will + be scheduled. The value is refreshed by the + server after each run. If unspecified, it will + default to current server time, which means the + scan will be scheduled to start immediately. + interval_duration_days (int): + Required. The duration of time between + executions in days. + """ + + schedule_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + interval_duration_days = proto.Field( + proto.INT32, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + max_qps = proto.Field( + proto.INT32, + number=3, + ) + starting_urls = proto.RepeatedField( + proto.STRING, + number=4, + ) + authentication = proto.Field( + proto.MESSAGE, + number=5, + message=Authentication, + ) + user_agent = proto.Field( + proto.ENUM, + number=6, + enum=UserAgent, + ) + blacklist_patterns = proto.RepeatedField( + proto.STRING, + number=7, + ) + schedule = proto.Field( + proto.MESSAGE, + number=8, + message=Schedule, + ) + export_to_security_command_center = proto.Field( + proto.ENUM, + number=10, + enum=ExportToSecurityCommandCenter, + ) + risk_level = proto.Field( + proto.ENUM, + number=12, + enum=RiskLevel, + ) + managed_scan = proto.Field( + proto.BOOL, + number=13, + ) + static_ip_scan = proto.Field( + proto.BOOL, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py new file mode 100644 index 0000000..d7d7fbf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1', + manifest={ + 'ScanConfigError', + }, +) + + +class ScanConfigError(proto.Message): + r"""Defines a custom error message used by CreateScanConfig and + UpdateScanConfig APIs when scan configuration validation fails. + It is also reported as part of a ScanRunErrorTrace message if + scan validation fails due to a scan configuration error. + + Attributes: + code (google.cloud.websecurityscanner_v1.types.ScanConfigError.Code): + Output only. Indicates the reason code for a + configuration failure. + field_name (str): + Output only. Indicates the full name of the ScanConfig field + that triggers this error, for example "scan_config.max_qps". + This field is provided for troubleshooting purposes only and + its actual value can change in the future. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 44 + """ + _pb_options = {'allow_alias': True} + CODE_UNSPECIFIED = 0 + OK = 0 + INTERNAL_ERROR = 1 + APPENGINE_API_BACKEND_ERROR = 2 + APPENGINE_API_NOT_ACCESSIBLE = 3 + APPENGINE_DEFAULT_HOST_MISSING = 4 + CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 + CANNOT_USE_OWNER_ACCOUNT = 7 + COMPUTE_API_BACKEND_ERROR = 8 + COMPUTE_API_NOT_ACCESSIBLE = 9 + CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 + CUSTOM_LOGIN_URL_MALFORMED = 11 + CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 + CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 + CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 + CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 + DUPLICATE_SCAN_NAME = 16 + INVALID_FIELD_VALUE = 18 + FAILED_TO_AUTHENTICATE_TO_TARGET = 19 + FINDING_TYPE_UNSPECIFIED = 20 + FORBIDDEN_TO_SCAN_COMPUTE = 21 + FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 + MALFORMED_FILTER = 22 + MALFORMED_RESOURCE_NAME = 23 + PROJECT_INACTIVE = 24 + REQUIRED_FIELD = 25 + RESOURCE_NAME_INCONSISTENT = 26 + SCAN_ALREADY_RUNNING = 27 + SCAN_NOT_RUNNING = 28 + SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 + SEED_URL_MALFORMED = 30 + SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 + SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 + SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 + SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 + SERVICE_ACCOUNT_NOT_CONFIGURED = 36 + TOO_MANY_SCANS = 37 + UNABLE_TO_RESOLVE_PROJECT_INFO = 38 + UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 + UNSUPPORTED_FILTER = 40 + UNSUPPORTED_FINDING_TYPE = 41 + UNSUPPORTED_URL_SCHEME = 42 + + code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + field_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py new file mode 100644 index 0000000..1097804 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRun', + }, +) + + +class ScanRun(proto.Message): + r"""A ScanRun is a output-only resource representing an actual + run of the scan. Next id: 12 + + Attributes: + name (str): + Output only. The resource name of the + ScanRun. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + The ScanRun IDs are generated by the system. + execution_state (google.cloud.websecurityscanner_v1.types.ScanRun.ExecutionState): + Output only. The execution state of the + ScanRun. + result_state (google.cloud.websecurityscanner_v1.types.ScanRun.ResultState): + Output only. The result state of the ScanRun. + This field is only available after the execution + state reaches "FINISHED". + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the ScanRun + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the ScanRun + reached termination state - that the ScanRun is + either finished or stopped by user. + urls_crawled_count (int): + Output only. The number of URLs crawled + during this ScanRun. If the scan is in progress, + the value represents the number of URLs crawled + up to now. + urls_tested_count (int): + Output only. The number of URLs tested during + this ScanRun. If the scan is in progress, the + value represents the number of URLs tested up to + now. The number of URLs tested is usually larger + than the number URLS crawled because typically a + crawled URL is tested with multiple test + payloads. + has_vulnerabilities (bool): + Output only. Whether the scan run has found + any vulnerabilities. + progress_percent (int): + Output only. The percentage of total + completion ranging from 0 to 100. If the scan is + in queue, the value is 0. If the scan is + running, the value ranges from 0 to 100. If the + scan is finished, the value is 100. + error_trace (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace): + Output only. If result_state is an ERROR, this field + provides the primary reason for scan's termination and more + details, if such are available. + warning_traces (Sequence[google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace]): + Output only. A list of warnings, if such are + encountered during this scan run. + """ + class ExecutionState(proto.Enum): + r"""Types of ScanRun execution state.""" + EXECUTION_STATE_UNSPECIFIED = 0 + QUEUED = 1 + SCANNING = 2 + FINISHED = 3 + + class ResultState(proto.Enum): + r"""Types of ScanRun result state.""" + RESULT_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + ERROR = 2 + KILLED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + execution_state = proto.Field( + proto.ENUM, + number=2, + enum=ExecutionState, + ) + result_state = proto.Field( + proto.ENUM, + number=3, + enum=ResultState, + ) + start_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + urls_crawled_count = proto.Field( + proto.INT64, + number=6, + ) + urls_tested_count = proto.Field( + proto.INT64, + number=7, + ) + has_vulnerabilities = proto.Field( + proto.BOOL, + number=8, + ) + progress_percent = proto.Field( + proto.INT32, + number=9, + ) + error_trace = proto.Field( + proto.MESSAGE, + number=10, + message=scan_run_error_trace.ScanRunErrorTrace, + ) + warning_traces = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=scan_run_warning_trace.ScanRunWarningTrace, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py new file mode 100644 index 0000000..ef970e5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.websecurityscanner_v1.types import scan_config_error as gcw_scan_config_error + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRunErrorTrace', + }, +) + + +class ScanRunErrorTrace(proto.Message): + r"""Output only. + Defines an error trace message for a ScanRun. + + Attributes: + code (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace.Code): + Output only. Indicates the error reason code. + scan_config_error (google.cloud.websecurityscanner_v1.types.ScanConfigError): + Output only. If the scan encounters SCAN_CONFIG_ISSUE error, + this field has the error message encountered during scan + configuration validation that is performed before each scan + run. + most_common_http_error_code (int): + Output only. If the scan encounters TOO_MANY_HTTP_ERRORS, + this field indicates the most common HTTP error code, if + such is available. For example, if this code is 404, the + scan has encountered too many NOT_FOUND responses. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 7 + """ + CODE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + SCAN_CONFIG_ISSUE = 2 + AUTHENTICATION_CONFIG_ISSUE = 3 + TIMED_OUT_WHILE_SCANNING = 4 + TOO_MANY_REDIRECTS = 5 + TOO_MANY_HTTP_ERRORS = 6 + + code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + scan_config_error = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config_error.ScanConfigError, + ) + most_common_http_error_code = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py new file mode 100644 index 0000000..e0ef98d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'ScanRunWarningTrace', + }, +) + + +class ScanRunWarningTrace(proto.Message): + r"""Output only. + Defines a warning trace message for ScanRun. Warning traces + provide customers with useful information that helps make the + scanning process more effective. + + Attributes: + code (google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace.Code): + Output only. Indicates the warning code. + """ + class Code(proto.Enum): + r"""Output only. + Defines a warning message code. + Next id: 6 + """ + CODE_UNSPECIFIED = 0 + INSUFFICIENT_CRAWL_RESULTS = 1 + TOO_MANY_CRAWL_RESULTS = 2 + TOO_MANY_FUZZ_TASKS = 3 + BLOCKED_BY_IAP = 4 + + code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py new file mode 100644 index 0000000..a40ea76 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py @@ -0,0 +1,462 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_type_stats as gcw_finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1', + manifest={ + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetScanConfigRequest', + 'ListScanConfigsRequest', + 'UpdateScanConfigRequest', + 'ListScanConfigsResponse', + 'StartScanRunRequest', + 'GetScanRunRequest', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StopScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'GetFindingRequest', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + }, +) + + +class CreateScanConfigRequest(proto.Message): + r"""Request for the ``CreateScanConfig`` method. + Attributes: + parent (str): + Required. The parent resource name where the + scan is created, which should be a project + resource name in the format + 'projects/{projectId}'. + scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): + Required. The ScanConfig to be created. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + scan_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + + +class DeleteScanConfigRequest(proto.Message): + r"""Request for the ``DeleteScanConfig`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be deleted. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanConfigRequest(proto.Message): + r"""Request for the ``GetScanConfig`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanConfigsRequest(proto.Message): + r"""Request for the ``ListScanConfigs`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a project resource name in the format + 'projects/{projectId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanConfigs to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class UpdateScanConfigRequest(proto.Message): + r"""Request for the ``UpdateScanConfigRequest`` method. + Attributes: + scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): + Required. The ScanConfig to be updated. The + name field must be set to identify the resource + to be updated. The values of fields not covered + by the mask will be ignored. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + """ + + scan_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListScanConfigsResponse(proto.Message): + r"""Response for the ``ListScanConfigs`` method. + Attributes: + scan_configs (Sequence[google.cloud.websecurityscanner_v1.types.ScanConfig]): + The list of ScanConfigs returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_scan_config.ScanConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class StartScanRunRequest(proto.Message): + r"""Request for the ``StartScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be used. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanRunRequest(proto.Message): + r"""Request for the ``GetScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanRun to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanRunsRequest(proto.Message): + r"""Request for the ``ListScanRuns`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanRuns to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListScanRunsResponse(proto.Message): + r"""Response for the ``ListScanRuns`` method. + Attributes: + scan_runs (Sequence[google.cloud.websecurityscanner_v1.types.ScanRun]): + The list of ScanRuns returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_runs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=scan_run.ScanRun, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class StopScanRunRequest(proto.Message): + r"""Request for the ``StopScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanRun to + be stopped. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCrawledUrlsRequest(proto.Message): + r"""Request for the ``ListCrawledUrls`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of CrawledUrls to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCrawledUrlsResponse(proto.Message): + r"""Response for the ``ListCrawledUrls`` method. + Attributes: + crawled_urls (Sequence[google.cloud.websecurityscanner_v1.types.CrawledUrl]): + The list of CrawledUrls returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + crawled_urls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=crawled_url.CrawledUrl, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFindingRequest(proto.Message): + r"""Request for the ``GetFinding`` method. + Attributes: + name (str): + Required. The resource name of the Finding to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request for the ``ListFindings`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + filter (str): + The filter expression. The expression must be in the format: + . Supported field: 'finding_type'. Supported operator: '='. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of Findings to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response for the ``ListFindings`` method. + Attributes: + findings (Sequence[google.cloud.websecurityscanner_v1.types.Finding]): + The list of Findings returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + findings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=finding.Finding, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingTypeStatsRequest(proto.Message): + r"""Request for the ``ListFindingTypeStats`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingTypeStatsResponse(proto.Message): + r"""Response for the ``ListFindingTypeStats`` method. + Attributes: + finding_type_stats (Sequence[google.cloud.websecurityscanner_v1.types.FindingTypeStats]): + The list of FindingTypeStats returned. + """ + + finding_type_stats = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_finding_type_stats.FindingTypeStats, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..ced81d4 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/websecurityscanner_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py new file mode 100644 index 0000000..5dd19da --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py @@ -0,0 +1,188 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class websecurityscannerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', '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: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=websecurityscannerCallTransformer(), +): + """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 websecurityscanner client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..a33245a --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-websecurityscanner', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py b/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py new file mode 100644 index 0000000..1f2ecbb --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py @@ -0,0 +1,3877 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerAsyncClient +from google.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1.services.web_security_scanner import transports +from google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.websecurityscanner_v1.types import crawled_url +from google.cloud.websecurityscanner_v1.types import finding +from google.cloud.websecurityscanner_v1.types import finding_addon +from google.cloud.websecurityscanner_v1.types import finding_type_stats +from google.cloud.websecurityscanner_v1.types import scan_config +from google.cloud.websecurityscanner_v1.types import scan_run +from google.cloud.websecurityscanner_v1.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1.types import web_security_scanner +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert WebSecurityScannerClient._get_default_mtls_endpoint(None) is None + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + WebSecurityScannerClient, + WebSecurityScannerAsyncClient, +]) +def test_web_security_scanner_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WebSecurityScannerGrpcTransport, "grpc"), + (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + WebSecurityScannerClient, + WebSecurityScannerAsyncClient, +]) +def test_web_security_scanner_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +def test_web_security_scanner_client_get_transport_class(): + transport = WebSecurityScannerClient.get_transport_class() + available_transports = [ + transports.WebSecurityScannerGrpcTransport, + ] + assert transport in available_transports + + transport = WebSecurityScannerClient.get_transport_class("grpc") + assert transport == transports.WebSecurityScannerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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(WebSecurityScannerClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(WebSecurityScannerClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_web_security_scanner_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_web_security_scanner_client_client_options_from_dict(): + with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebSecurityScannerClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_scan_config(transport: str = 'grpc', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ) + response = client.create_scan_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] == web_security_scanner.CreateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + + +def test_create_scan_config_from_dict(): + test_create_scan_config(request_type=dict) + + +def test_create_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + client.create_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest() + + +@pytest.mark.asyncio +async def test_create_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + )) + response = await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + + +@pytest.mark.asyncio +async def test_create_scan_config_async_from_dict(): + await test_create_scan_config_async(request_type=dict) + + +def test_create_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.create_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.create_scan_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_delete_scan_config(transport: str = 'grpc', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scan_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] == web_security_scanner.DeleteScanConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_from_dict(): + test_delete_scan_config(request_type=dict) + + +def test_delete_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + client.delete_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_scan_config_async_from_dict(): + await test_delete_scan_config_async(request_type=dict) + + +def test_delete_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_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_scan_config(transport: str = 'grpc', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ) + response = client.get_scan_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] == web_security_scanner.GetScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + + +def test_get_scan_config_from_dict(): + test_get_scan_config(request_type=dict) + + +def test_get_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + client.get_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest() + + +@pytest.mark.asyncio +async def test_get_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + )) + response = await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + + +@pytest.mark.asyncio +async def test_get_scan_config_async_from_dict(): + await test_get_scan_config_async(request_type=dict) + + +def test_get_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.get_scan_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_list_scan_configs(transport: str = 'grpc', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_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] == web_security_scanner.ListScanConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_configs_from_dict(): + test_list_scan_configs(request_type=dict) + + +def test_list_scan_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + client.list_scan_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_from_dict(): + await test_list_scan_configs_async(request_type=dict) + + +def test_list_scan_configs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_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_scan_configs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + await client.list_scan_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_scan_configs_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_configs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) + for i in results) + +def test_list_scan_configs_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_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_scan_configs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_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, scan_config.ScanConfig) + for i in responses) + +@pytest.mark.asyncio +async def test_list_scan_configs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_scan_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_update_scan_config(transport: str = 'grpc', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ) + response = client.update_scan_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] == web_security_scanner.UpdateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + + +def test_update_scan_config_from_dict(): + test_update_scan_config(request_type=dict) + + +def test_update_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + client.update_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest() + + +@pytest.mark.asyncio +async def test_update_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + )) + response = await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + + +@pytest.mark.asyncio +async def test_update_scan_config_async_from_dict(): + await test_update_scan_config_async(request_type=dict) + + +def test_update_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'scan_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.update_scan_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', + 'scan_config.name=scan_config.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'scan_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.update_scan_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', + 'scan_config.name=scan_config.name/value', + ) in kw['metadata'] + + +def test_start_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_from_dict(): + test_start_scan_run(request_type=dict) + + +def test_start_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + client.start_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + +@pytest.mark.asyncio +async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_start_scan_run_async_from_dict(): + await test_start_scan_run_async(request_type=dict) + + +def test_start_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_start_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_scan_run(transport: str = 'grpc', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_from_dict(): + test_get_scan_run(request_type=dict) + + +def test_get_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + client.get_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + +@pytest.mark.asyncio +async def test_get_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_get_scan_run_async_from_dict(): + await test_get_scan_run_async(request_type=dict) + + +def test_get_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_list_scan_runs(transport: str = 'grpc', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_runs_from_dict(): + test_list_scan_runs(request_type=dict) + + +def test_list_scan_runs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + client.list_scan_runs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + +@pytest.mark.asyncio +async def test_list_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_from_dict(): + await test_list_scan_runs_async(request_type=dict) + + +def test_list_scan_runs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_scan_runs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_scan_runs_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_runs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) + for i in results) + +def test_list_scan_runs_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_runs(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_scan_runs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_runs(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, scan_run.ScanRun) + for i in responses) + +@pytest.mark.asyncio +async def test_list_scan_runs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_scan_runs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_stop_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_from_dict(): + test_stop_scan_run(request_type=dict) + + +def test_stop_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + client.stop_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + +@pytest.mark.asyncio +async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_stop_scan_run_async_from_dict(): + await test_stop_scan_run_async(request_type=dict) + + +def test_stop_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_stop_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_list_crawled_urls(transport: str = 'grpc', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_crawled_urls_from_dict(): + test_list_crawled_urls(request_type=dict) + + +def test_list_crawled_urls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + client.list_crawled_urls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_from_dict(): + await test_list_crawled_urls_async(request_type=dict) + + +def test_list_crawled_urls_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_crawled_urls_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_crawled_urls_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crawled_urls(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) + for i in results) + +def test_list_crawled_urls_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in responses) + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_crawled_urls(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_finding(transport: str = 'grpc', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + finding_type='finding_type_value', + severity=finding.Finding.Severity.CRITICAL, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + response = client.get_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] == web_security_scanner.GetFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +def test_get_finding_from_dict(): + test_get_finding(request_type=dict) + + +def test_get_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + client.get_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest() + + +@pytest.mark.asyncio +async def test_get_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type='finding_type_value', + severity=finding.Finding.Severity.CRITICAL, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + response = await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.asyncio +async def test_get_finding_async_from_dict(): + await test_get_finding_async(request_type=dict) + + +def test_get_finding_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_finding_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_list_findings(transport: str = 'grpc', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + ) + 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] == web_security_scanner.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' + + +def test_list_findings_from_dict(): + test_list_findings(request_type=dict) + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + 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] == web_security_scanner.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.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 = web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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_finding_type_stats(transport: str = 'grpc', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse( + ) + response = client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_from_dict(): + test_list_finding_type_stats(request_type=dict) + + +def test_list_finding_type_stats_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + client.list_finding_type_stats() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + response = await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async_from_dict(): + await test_list_finding_type_stats_async(request_type=dict) + + +def test_list_finding_type_stats_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_finding_type_stats_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_scan_config', + 'delete_scan_config', + 'get_scan_config', + 'list_scan_configs', + 'update_scan_config', + 'start_scan_run', + 'get_scan_run', + 'list_scan_runs', + 'stop_scan_run', + 'list_crawled_urls', + 'get_finding', + 'list_findings', + 'list_finding_type_stats', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + 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_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebSecurityScannerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebSecurityScannerClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebSecurityScannerGrpcTransport, grpc_helpers), + (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_web_security_scanner_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "websecurityscanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_web_security_scanner_host_no_port(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), + ) + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +def test_web_security_scanner_host_with_port(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), + ) + assert client.transport._host == 'websecurityscanner.googleapis.com:8000' + +def test_web_security_scanner_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_web_security_scanner_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_finding_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + finding = "octopus" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "project": "oyster", + "scan_config": "nudibranch", + "scan_run": "cuttlefish", + "finding": "mussel", + } + path = WebSecurityScannerClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_finding_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebSecurityScannerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = WebSecurityScannerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebSecurityScannerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = WebSecurityScannerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebSecurityScannerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = WebSecurityScannerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = WebSecurityScannerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = WebSecurityScannerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = WebSecurityScannerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = WebSecurityScannerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + transport_class = WebSecurityScannerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc new file mode 100644 index 0000000..6b433c1 --- /dev/null +++ b/owl-bot-staging/v1alpha/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/websecurityscanner/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in new file mode 100644 index 0000000..984c53e --- /dev/null +++ b/owl-bot-staging/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/websecurityscanner *.py +recursive-include google/cloud/websecurityscanner_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst new file mode 100644 index 0000000..4de4c10 --- /dev/null +++ b/owl-bot-staging/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Websecurityscanner API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Websecurityscanner API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py new file mode 100644 index 0000000..c393cbd --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-websecurityscanner documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-websecurityscanner" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-websecurityscanner-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-websecurityscanner.tex", + u"google-cloud-websecurityscanner Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-websecurityscanner", + u"Google Cloud Websecurityscanner Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-websecurityscanner", + u"google-cloud-websecurityscanner Documentation", + author, + "google-cloud-websecurityscanner", + "GAPIC library for Google Cloud Websecurityscanner API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst new file mode 100644 index 0000000..d13b957 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + websecurityscanner_v1alpha/services + websecurityscanner_v1alpha/types diff --git a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst new file mode 100644 index 0000000..a4ad413 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Websecurityscanner v1alpha API +======================================================== +.. toctree:: + :maxdepth: 2 + + web_security_scanner diff --git a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst new file mode 100644 index 0000000..0f6d569 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Websecurityscanner v1alpha API +===================================================== + +.. automodule:: google.cloud.websecurityscanner_v1alpha.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst new file mode 100644 index 0000000..1bb5688 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst @@ -0,0 +1,10 @@ +WebSecurityScanner +------------------------------------ + +.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner + :members: + :inherited-members: + +.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py new file mode 100644 index 0000000..a25e69d --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1alpha.services.web_security_scanner.client import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient + +from google.cloud.websecurityscanner_v1alpha.types.crawled_url import CrawledUrl +from google.cloud.websecurityscanner_v1alpha.types.finding import Finding +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import OutdatedLibrary +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import ViolatingResource +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableHeaders +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableParameters +from google.cloud.websecurityscanner_v1alpha.types.finding_addon import Xss +from google.cloud.websecurityscanner_v1alpha.types.finding_type_stats import FindingTypeStats +from google.cloud.websecurityscanner_v1alpha.types.scan_config import ScanConfig +from google.cloud.websecurityscanner_v1alpha.types.scan_run import ScanRun +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import CreateScanConfigRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import DeleteScanConfigRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetFindingRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanConfigRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanRunRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsResponse +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StartScanRunRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StopScanRunRequest +from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ('WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', + 'CrawledUrl', + 'Finding', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanRun', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed new file mode 100644 index 0000000..8cfb5d2 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py new file mode 100644 index 0000000..423e06e --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.web_security_scanner import WebSecurityScannerClient +from .services.web_security_scanner import WebSecurityScannerAsyncClient + +from .types.crawled_url import CrawledUrl +from .types.finding import Finding +from .types.finding_addon import OutdatedLibrary +from .types.finding_addon import ViolatingResource +from .types.finding_addon import VulnerableHeaders +from .types.finding_addon import VulnerableParameters +from .types.finding_addon import Xss +from .types.finding_type_stats import FindingTypeStats +from .types.scan_config import ScanConfig +from .types.scan_run import ScanRun +from .types.web_security_scanner import CreateScanConfigRequest +from .types.web_security_scanner import DeleteScanConfigRequest +from .types.web_security_scanner import GetFindingRequest +from .types.web_security_scanner import GetScanConfigRequest +from .types.web_security_scanner import GetScanRunRequest +from .types.web_security_scanner import ListCrawledUrlsRequest +from .types.web_security_scanner import ListCrawledUrlsResponse +from .types.web_security_scanner import ListFindingsRequest +from .types.web_security_scanner import ListFindingsResponse +from .types.web_security_scanner import ListFindingTypeStatsRequest +from .types.web_security_scanner import ListFindingTypeStatsResponse +from .types.web_security_scanner import ListScanConfigsRequest +from .types.web_security_scanner import ListScanConfigsResponse +from .types.web_security_scanner import ListScanRunsRequest +from .types.web_security_scanner import ListScanRunsResponse +from .types.web_security_scanner import StartScanRunRequest +from .types.web_security_scanner import StopScanRunRequest +from .types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ( + 'WebSecurityScannerAsyncClient', +'CrawledUrl', +'CreateScanConfigRequest', +'DeleteScanConfigRequest', +'Finding', +'FindingTypeStats', +'GetFindingRequest', +'GetScanConfigRequest', +'GetScanRunRequest', +'ListCrawledUrlsRequest', +'ListCrawledUrlsResponse', +'ListFindingTypeStatsRequest', +'ListFindingTypeStatsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListScanConfigsRequest', +'ListScanConfigsResponse', +'ListScanRunsRequest', +'ListScanRunsResponse', +'OutdatedLibrary', +'ScanConfig', +'ScanRun', +'StartScanRunRequest', +'StopScanRunRequest', +'UpdateScanConfigRequest', +'ViolatingResource', +'VulnerableHeaders', +'VulnerableParameters', +'WebSecurityScannerClient', +'Xss', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json new file mode 100644 index 0000000..f43f913 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json @@ -0,0 +1,153 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.websecurityscanner_v1alpha", + "protoPackage": "google.cloud.websecurityscanner.v1alpha", + "schema": "1.0", + "services": { + "WebSecurityScanner": { + "clients": { + "grpc": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebSecurityScannerAsyncClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed new file mode 100644 index 0000000..8cfb5d2 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py new file mode 100644 index 0000000..46b053b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import WebSecurityScannerClient +from .async_client import WebSecurityScannerAsyncClient + +__all__ = ( + 'WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py new file mode 100644 index 0000000..fbef3ec --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py @@ -0,0 +1,1314 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_addon +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .client import WebSecurityScannerClient + + +class WebSecurityScannerAsyncClient: + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + _client: WebSecurityScannerClient + + DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + + finding_path = staticmethod(WebSecurityScannerClient.finding_path) + parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) + scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) + parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) + scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) + parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) + common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) + parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) + common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) + parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) + common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) + parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) + common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) + parse_common_location_path = staticmethod(WebSecurityScannerClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WebSecurityScannerClient).get_transport_class, type(WebSecurityScannerClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, WebSecurityScannerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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, ~.WebSecurityScannerTransport]): 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 = WebSecurityScannerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_scan_config(self, + request: web_security_scanner.CreateScanConfigRequest = None, + *, + parent: str = None, + scan_config: gcw_scan_config.ScanConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest`): + The request object. Request for the `CreateScanConfig` + method. + parent (:class:`str`): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity 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, scan_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.CreateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_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_scan_config, + default_timeout=600.0, + client_info=DEFAULT_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_scan_config(self, + request: web_security_scanner.DeleteScanConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest`): + The request object. Request for the `DeleteScanConfig` + method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.DeleteScanConfigRequest(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_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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_scan_config(self, + request: web_security_scanner.GetScanConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest`): + The request object. Request for the `GetScanConfig` + method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.GetScanConfigRequest(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_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_scan_configs(self, + request: web_security_scanner.ListScanConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsAsyncPager: + r"""Lists ScanConfigs under a given project. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest`): + The request object. Request for the `ListScanConfigs` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: + Response for the ListScanConfigs method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListScanConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scan_config(self, + request: web_security_scanner.UpdateScanConfigRequest = None, + *, + scan_config: gcw_scan_config.ScanConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest`): + The request object. Request for the + `UpdateScanConfigRequest` method. + scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.UpdateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_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_scan_config, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def start_scan_run(self, + request: web_security_scanner.StartScanRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest`): + The request object. Request for the `StartScanRun` + method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.StartScanRunRequest(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.start_scan_run, + default_timeout=600.0, + client_info=DEFAULT_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_scan_run(self, + request: web_security_scanner.GetScanRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest`): + The request object. Request for the `GetScanRun` method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.GetScanRunRequest(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_scan_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_scan_runs(self, + request: web_security_scanner.ListScanRunsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsAsyncPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest`): + The request object. Request for the `ListScanRuns` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsAsyncPager: + Response for the ListScanRuns method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListScanRunsRequest(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_scan_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListScanRunsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_scan_run(self, + request: web_security_scanner.StopScanRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest`): + The request object. Request for the `StopScanRun` + method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.StopScanRunRequest(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.stop_scan_run, + default_timeout=600.0, + client_info=DEFAULT_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 list_crawled_urls(self, + request: web_security_scanner.ListCrawledUrlsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsAsyncPager: + r"""List CrawledUrls under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest`): + The request object. Request for the `ListCrawledUrls` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: + Response for the ListCrawledUrls method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListCrawledUrlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_finding(self, + request: web_security_scanner.GetFindingRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest`): + The request object. Request for the `GetFinding` method. + name (:class:`str`): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.GetFindingRequest(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_finding, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_findings(self, + request: web_security_scanner.ListFindingsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""List Findings under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest`): + The request object. Request for the `ListFindings` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsAsyncPager: + Response for the ListFindings method. + + 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, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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_finding_type_stats(self, + request: web_security_scanner.ListFindingTypeStatsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest`): + The request object. Request for the + `ListFindingTypeStats` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats 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([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-websecurityscanner", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebSecurityScannerAsyncClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py new file mode 100644 index 0000000..88ca30c --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py @@ -0,0 +1,1460 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_addon +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebSecurityScannerGrpcTransport +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport + + +class WebSecurityScannerClientMeta(type): + """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] + _transport_registry["grpc"] = WebSecurityScannerGrpcTransport + _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[WebSecurityScannerTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "websecurityscanner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_config_path(project: str,scan_config: str,) -> str: + """Returns a fully-qualified scan_config string.""" + return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + + @staticmethod + def parse_scan_config_path(path: str) -> Dict[str,str]: + """Parses a scan_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: + """Returns a fully-qualified scan_run string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + + @staticmethod + def parse_scan_run_path(path: str) -> Dict[str,str]: + """Parses a scan_run path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, WebSecurityScannerTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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, WebSecurityScannerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, WebSecurityScannerTransport): + # transport is a WebSecurityScannerTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_scan_config(self, + request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, + *, + parent: str = None, + scan_config: gcw_scan_config.ScanConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]): + The request object. Request for the `CreateScanConfig` + method. + parent (str): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity 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, scan_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 web_security_scanner.CreateScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scan_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_scan_config(self, + request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]): + The request object. Request for the `DeleteScanConfig` + method. + name (str): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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 web_security_scanner.DeleteScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(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_scan_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_scan_config(self, + request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]): + The request object. Request for the `GetScanConfig` + method. + name (str): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.GetScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(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_scan_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 list_scan_configs(self, + request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsPager: + r"""Lists ScanConfigs under a given project. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]): + The request object. Request for the `ListScanConfigs` + method. + parent (str): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsPager: + Response for the ListScanConfigs method. + + 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 web_security_scanner.ListScanConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_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.ListScanConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scan_config(self, + request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, + *, + scan_config: gcw_scan_config.ScanConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]): + The request object. Request for the + `UpdateScanConfigRequest` method. + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_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 web_security_scanner.UpdateScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_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_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def start_scan_run(self, + request: Union[web_security_scanner.StartScanRunRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]): + The request object. Request for the `StartScanRun` + method. + name (str): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.StartScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(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.start_scan_run] + + # 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_scan_run(self, + request: Union[web_security_scanner.GetScanRunRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]): + The request object. Request for the `GetScanRun` method. + name (str): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.GetScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(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_scan_run] + + # 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 list_scan_runs(self, + request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]): + The request object. Request for the `ListScanRuns` + method. + parent (str): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsPager: + Response for the ListScanRuns method. + + 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 web_security_scanner.ListScanRunsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # 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.ListScanRunsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_scan_run(self, + request: Union[web_security_scanner.StopScanRunRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]): + The request object. Request for the `StopScanRun` + method. + name (str): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.StopScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(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.stop_scan_run] + + # 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 list_crawled_urls(self, + request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsPager: + r"""List CrawledUrls under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]): + The request object. Request for the `ListCrawledUrls` + method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsPager: + Response for the ListCrawledUrls method. + + 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 web_security_scanner.ListCrawledUrlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # 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.ListCrawledUrlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_finding(self, + request: Union[web_security_scanner.GetFindingRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]): + The request object. Request for the `GetFinding` method. + name (str): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.GetFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(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_finding] + + # 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 list_findings(self, + request: Union[web_security_scanner.ListFindingsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""List Findings under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]): + The request object. Request for the `ListFindings` + method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsPager: + Response for the ListFindings method. + + 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, filter]) + if request is 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 web_security_scanner.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_finding_type_stats(self, + request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]): + The request object. Request for the + `ListFindingTypeStats` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats 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([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 web_security_scanner.ListFindingTypeStatsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-websecurityscanner", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebSecurityScannerClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py new file mode 100644 index 0000000..c3acaf3 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner + + +class ListScanConfigsPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` + 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[..., web_security_scanner.ListScanConfigsResponse], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): + 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 = web_security_scanner.ListScanConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + for page in self.pages: + yield from page.scan_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanConfigsAsyncPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` + 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[web_security_scanner.ListScanConfigsResponse]], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): + 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 = web_security_scanner.ListScanConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` + 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[..., web_security_scanner.ListScanRunsResponse], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): + 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 = web_security_scanner.ListScanRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + for page in self.pages: + yield from page.scan_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsAsyncPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` + 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[web_security_scanner.ListScanRunsResponse]], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): + 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 = web_security_scanner.ListScanRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` + 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[..., web_security_scanner.ListCrawledUrlsResponse], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): + 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 = web_security_scanner.ListCrawledUrlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + for page in self.pages: + yield from page.crawled_urls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsAsyncPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` + 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[web_security_scanner.ListCrawledUrlsResponse]], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): + 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 = web_security_scanner.ListCrawledUrlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + async def async_generator(): + async for page in self.pages: + for response in page.crawled_urls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListFindingsResponse], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[web_security_scanner.ListFindingsResponse]], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.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[web_security_scanner.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) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py new file mode 100644 index 0000000..19f4df5 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import WebSecurityScannerTransport +from .grpc import WebSecurityScannerGrpcTransport +from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] +_transport_registry['grpc'] = WebSecurityScannerGrpcTransport +_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport + +__all__ = ( + 'WebSecurityScannerTransport', + 'WebSecurityScannerGrpcTransport', + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py new file mode 100644 index 0000000..466c6ae --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py @@ -0,0 +1,404 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-websecurityscanner', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class WebSecurityScannerTransport(abc.ABC): + """Abstract transport class for WebSecurityScanner.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'websecurityscanner.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_scan_config: gapic_v1.method.wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: gapic_v1.method.wrap_method( + self.delete_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: gapic_v1.method.wrap_method( + self.get_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: gapic_v1.method.wrap_method( + self.list_scan_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: gapic_v1.method.wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: gapic_v1.method.wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: gapic_v1.method.wrap_method( + self.get_scan_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: gapic_v1.method.wrap_method( + self.list_scan_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: gapic_v1.method.wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: gapic_v1.method.wrap_method( + self.list_crawled_urls, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: gapic_v1.method.wrap_method( + self.get_finding, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: gapic_v1.method.wrap_method( + self.list_finding_type_stats, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Union[ + web_security_scanner.ListScanConfigsResponse, + Awaitable[web_security_scanner.ListScanConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Union[ + web_security_scanner.ListScanRunsResponse, + Awaitable[web_security_scanner.ListScanRunsResponse] + ]]: + raise NotImplementedError() + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Union[ + web_security_scanner.ListCrawledUrlsResponse, + Awaitable[web_security_scanner.ListCrawledUrlsResponse] + ]]: + raise NotImplementedError() + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Union[ + web_security_scanner.ListFindingsResponse, + Awaitable[web_security_scanner.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Union[ + web_security_scanner.ListFindingTypeStatsResponse, + Awaitable[web_security_scanner.ListFindingTypeStatsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'WebSecurityScannerTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py new file mode 100644 index 0000000..f8cf97a --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + + +class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): + """gRPC backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + 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 = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + ~.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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + ~.ListScanConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + ~.ListScanRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + ~.ListCrawledUrlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + ~.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 'get_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + 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.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + ~.ListFindingTypeStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + +__all__ = ( + 'WebSecurityScannerGrpcTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py new file mode 100644 index 0000000..ddeed45 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py @@ -0,0 +1,579 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .grpc import WebSecurityScannerGrpcTransport + + +class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): + """gRPC AsyncIO backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + 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 = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + 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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Awaitable[web_security_scanner.ListScanConfigsResponse]]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + Awaitable[~.ListScanConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Awaitable[web_security_scanner.ListScanRunsResponse]]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + Awaitable[~.ListScanRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + Awaitable[~.ListCrawledUrlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + 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 'get_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Awaitable[web_security_scanner.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + 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.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + Awaitable[~.ListFindingTypeStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + +__all__ = ( + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py new file mode 100644 index 0000000..c8502b8 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .crawled_url import ( + CrawledUrl, +) +from .finding import ( + Finding, +) +from .finding_addon import ( + OutdatedLibrary, + ViolatingResource, + VulnerableHeaders, + VulnerableParameters, + Xss, +) +from .finding_type_stats import ( + FindingTypeStats, +) +from .scan_config import ( + ScanConfig, +) +from .scan_run import ( + ScanRun, +) +from .web_security_scanner import ( + CreateScanConfigRequest, + DeleteScanConfigRequest, + GetFindingRequest, + GetScanConfigRequest, + GetScanRunRequest, + ListCrawledUrlsRequest, + ListCrawledUrlsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListFindingTypeStatsRequest, + ListFindingTypeStatsResponse, + ListScanConfigsRequest, + ListScanConfigsResponse, + ListScanRunsRequest, + ListScanRunsResponse, + StartScanRunRequest, + StopScanRunRequest, + UpdateScanConfigRequest, +) + +__all__ = ( + 'CrawledUrl', + 'Finding', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanRun', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py new file mode 100644 index 0000000..6b6ae8e --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1alpha', + manifest={ + 'CrawledUrl', + }, +) + + +class CrawledUrl(proto.Message): + r"""A CrawledUrl resource represents a URL that was crawled + during a ScanRun. Web Security Scanner Service crawls the web + applications, following all links within the scope of sites, to + find the URLs to test against. + + Attributes: + http_method (str): + Output only. The http method of the request + that was used to visit the URL, in uppercase. + url (str): + Output only. The URL that was crawled. + body (str): + Output only. The body of the request that was + used to visit the URL. + """ + + http_method = proto.Field( + proto.STRING, + number=1, + ) + url = proto.Field( + proto.STRING, + number=2, + ) + body = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py new file mode 100644 index 0000000..8fad051 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.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.websecurityscanner_v1alpha.types import finding_addon + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""A Finding resource represents a vulnerability instance + identified during a ScanRun. + + Attributes: + name (str): + The resource name of the Finding. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. + The finding IDs are generated by the system. + finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): + The type of the Finding. + http_method (str): + The http method of the request that triggered + the vulnerability, in uppercase. + fuzzed_url (str): + The URL produced by the server-side fuzzer + and used in the request that triggered the + vulnerability. + body (str): + The body of the request that triggered the + vulnerability. + description (str): + The description of the vulnerability. + reproduction_url (str): + The URL containing human-readable payload + that user can leverage to reproduce the + vulnerability. + frame_url (str): + If the vulnerability was originated from + nested IFrame, the immediate parent IFrame is + reported. + final_url (str): + The URL where the browser lands when the + vulnerability is detected. + tracking_id (str): + The tracking ID uniquely identifies a + vulnerability instance across multiple ScanRuns. + outdated_library (google.cloud.websecurityscanner_v1alpha.types.OutdatedLibrary): + An addon containing information about + outdated libraries. + violating_resource (google.cloud.websecurityscanner_v1alpha.types.ViolatingResource): + An addon containing detailed information + regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, + etc. + vulnerable_headers (google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders): + An addon containing information about + vulnerable or missing HTTP headers. + vulnerable_parameters (google.cloud.websecurityscanner_v1alpha.types.VulnerableParameters): + An addon containing information about request + parameters which were found to be vulnerable. + xss (google.cloud.websecurityscanner_v1alpha.types.Xss): + An addon containing information reported for + an XSS, if any. + """ + class FindingType(proto.Enum): + r"""Types of Findings.""" + FINDING_TYPE_UNSPECIFIED = 0 + MIXED_CONTENT = 1 + OUTDATED_LIBRARY = 2 + ROSETTA_FLASH = 5 + XSS_CALLBACK = 3 + XSS_ERROR = 4 + CLEAR_TEXT_PASSWORD = 6 + INVALID_CONTENT_TYPE = 7 + XSS_ANGULAR_CALLBACK = 8 + INVALID_HEADER = 9 + MISSPELLED_SECURITY_HEADER_NAME = 10 + MISMATCHING_SECURITY_HEADER_VALUES = 11 + + name = proto.Field( + proto.STRING, + number=1, + ) + finding_type = proto.Field( + proto.ENUM, + number=2, + enum=FindingType, + ) + http_method = proto.Field( + proto.STRING, + number=3, + ) + fuzzed_url = proto.Field( + proto.STRING, + number=4, + ) + body = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + reproduction_url = proto.Field( + proto.STRING, + number=7, + ) + frame_url = proto.Field( + proto.STRING, + number=8, + ) + final_url = proto.Field( + proto.STRING, + number=9, + ) + tracking_id = proto.Field( + proto.STRING, + number=10, + ) + outdated_library = proto.Field( + proto.MESSAGE, + number=11, + message=finding_addon.OutdatedLibrary, + ) + violating_resource = proto.Field( + proto.MESSAGE, + number=12, + message=finding_addon.ViolatingResource, + ) + vulnerable_headers = proto.Field( + proto.MESSAGE, + number=15, + message=finding_addon.VulnerableHeaders, + ) + vulnerable_parameters = proto.Field( + proto.MESSAGE, + number=13, + message=finding_addon.VulnerableParameters, + ) + xss = proto.Field( + proto.MESSAGE, + number=14, + message=finding_addon.Xss, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py new file mode 100644 index 0000000..ec36cd1 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableParameters', + 'VulnerableHeaders', + 'Xss', + }, +) + + +class OutdatedLibrary(proto.Message): + r"""Information reported for an outdated library. + Attributes: + library_name (str): + The name of the outdated library. + version (str): + The version number. + learn_more_urls (Sequence[str]): + URLs to learn more information about the + vulnerabilities in the library. + """ + + library_name = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + learn_more_urls = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ViolatingResource(proto.Message): + r"""Information regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, etc. + + Attributes: + content_type (str): + The MIME type of this resource. + resource_url (str): + URL of this violating resource. + """ + + content_type = proto.Field( + proto.STRING, + number=1, + ) + resource_url = proto.Field( + proto.STRING, + number=2, + ) + + +class VulnerableParameters(proto.Message): + r"""Information about vulnerable request parameters. + Attributes: + parameter_names (Sequence[str]): + The vulnerable parameter names. + """ + + parameter_names = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VulnerableHeaders(proto.Message): + r"""Information about vulnerable or missing HTTP Headers. + Attributes: + headers (Sequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): + List of vulnerable headers. + missing_headers (Sequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): + List of missing headers. + """ + + class Header(proto.Message): + r"""Describes a HTTP Header. + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.STRING, + number=2, + ) + + headers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Header, + ) + missing_headers = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Header, + ) + + +class Xss(proto.Message): + r"""Information reported for an XSS. + Attributes: + stack_traces (Sequence[str]): + Stack traces leading to the point where the + XSS occurred. + error_message (str): + An error message generated by a javascript + breakage. + """ + + stack_traces = proto.RepeatedField( + proto.STRING, + number=1, + ) + error_message = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py new file mode 100644 index 0000000..12f5ad8 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.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.cloud.websecurityscanner_v1alpha.types import finding + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'FindingTypeStats', + }, +) + + +class FindingTypeStats(proto.Message): + r"""A FindingTypeStats resource represents stats regarding a + specific FindingType of Findings under a given ScanRun. + + Attributes: + finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): + The finding type associated with the stats. + finding_count (int): + The count of findings belonging to this + finding type. + """ + + finding_type = proto.Field( + proto.ENUM, + number=1, + enum=finding.Finding.FindingType, + ) + finding_count = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py new file mode 100644 index 0000000..03adc0e --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1alpha.types import scan_run +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'ScanConfig', + }, +) + + +class ScanConfig(proto.Message): + r"""A ScanConfig resource contains the configurations to launch a + scan. next id: 12 + + Attributes: + name (str): + The resource name of the ScanConfig. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + The ScanConfig IDs are generated by the system. + display_name (str): + Required. The user provided display name of + the ScanConfig. + max_qps (int): + The maximum QPS during scanning. A valid value ranges from 5 + to 20 inclusively. If the field is unspecified or its value + is set 0, server will default to 15. Other values outside of + [5, 20] range will be rejected with INVALID_ARGUMENT error. + starting_urls (Sequence[str]): + Required. The starting URLs from which the + scanner finds site pages. + authentication (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication): + The authentication configuration. If + specified, service will use the authentication + configuration during scanning. + user_agent (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.UserAgent): + The user agent used during scanning. + blacklist_patterns (Sequence[str]): + The blacklist URL patterns as described in + https://cloud.google.com/security- + scanner/docs/excluded-urls + schedule (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Schedule): + The schedule of the ScanConfig. + target_platforms (Sequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig.TargetPlatform]): + Set of Cloud Platforms targeted by the scan. If empty, + APP_ENGINE will be used as a default. + latest_run (google.cloud.websecurityscanner_v1alpha.types.ScanRun): + Latest ScanRun if available. + """ + class UserAgent(proto.Enum): + r"""Type of user agents used for scanning.""" + USER_AGENT_UNSPECIFIED = 0 + CHROME_LINUX = 1 + CHROME_ANDROID = 2 + SAFARI_IPHONE = 3 + + class TargetPlatform(proto.Enum): + r"""Cloud platforms supported by Cloud Web Security Scanner.""" + TARGET_PLATFORM_UNSPECIFIED = 0 + APP_ENGINE = 1 + COMPUTE = 2 + + class Authentication(proto.Message): + r"""Scan authentication configuration. + Attributes: + google_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.GoogleAccount): + Authentication using a Google account. + custom_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.CustomAccount): + Authentication using a custom account. + """ + + class GoogleAccount(proto.Message): + r"""Describes authentication configuration that uses a Google + account. + + Attributes: + username (str): + Required. The user name of the Google + account. + password (str): + Required. Input only. The password of the + Google account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + """ + + username = proto.Field( + proto.STRING, + number=1, + ) + password = proto.Field( + proto.STRING, + number=2, + ) + + class CustomAccount(proto.Message): + r"""Describes authentication configuration that uses a custom + account. + + Attributes: + username (str): + Required. The user name of the custom + account. + password (str): + Required. Input only. The password of the + custom account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + login_url (str): + Required. The login form URL of the website. + """ + + username = proto.Field( + proto.STRING, + number=1, + ) + password = proto.Field( + proto.STRING, + number=2, + ) + login_url = proto.Field( + proto.STRING, + number=3, + ) + + google_account = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication', + message='ScanConfig.Authentication.GoogleAccount', + ) + custom_account = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication', + message='ScanConfig.Authentication.CustomAccount', + ) + + class Schedule(proto.Message): + r"""Scan schedule configuration. + Attributes: + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + A timestamp indicates when the next run will + be scheduled. The value is refreshed by the + server after each run. If unspecified, it will + default to current server time, which means the + scan will be scheduled to start immediately. + interval_duration_days (int): + Required. The duration of time between + executions in days. + """ + + schedule_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + interval_duration_days = proto.Field( + proto.INT32, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + max_qps = proto.Field( + proto.INT32, + number=3, + ) + starting_urls = proto.RepeatedField( + proto.STRING, + number=4, + ) + authentication = proto.Field( + proto.MESSAGE, + number=5, + message=Authentication, + ) + user_agent = proto.Field( + proto.ENUM, + number=6, + enum=UserAgent, + ) + blacklist_patterns = proto.RepeatedField( + proto.STRING, + number=7, + ) + schedule = proto.Field( + proto.MESSAGE, + number=8, + message=Schedule, + ) + target_platforms = proto.RepeatedField( + proto.ENUM, + number=9, + enum=TargetPlatform, + ) + latest_run = proto.Field( + proto.MESSAGE, + number=11, + message=scan_run.ScanRun, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py new file mode 100644 index 0000000..310b999 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.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.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'ScanRun', + }, +) + + +class ScanRun(proto.Message): + r"""A ScanRun is a output-only resource representing an actual + run of the scan. + + Attributes: + name (str): + The resource name of the ScanRun. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + The ScanRun IDs are generated by the system. + execution_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ExecutionState): + The execution state of the ScanRun. + result_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ResultState): + The result state of the ScanRun. This field + is only available after the execution state + reaches "FINISHED". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun reached + termination state - that the ScanRun is either + finished or stopped by user. + urls_crawled_count (int): + The number of URLs crawled during this + ScanRun. If the scan is in progress, the value + represents the number of URLs crawled up to now. + urls_tested_count (int): + The number of URLs tested during this + ScanRun. If the scan is in progress, the value + represents the number of URLs tested up to now. + The number of URLs tested is usually larger than + the number URLS crawled because typically a + crawled URL is tested with multiple test + payloads. + has_vulnerabilities (bool): + Whether the scan run has found any + vulnerabilities. + progress_percent (int): + The percentage of total completion ranging + from 0 to 100. If the scan is in queue, the + value is 0. If the scan is running, the value + ranges from 0 to 100. If the scan is finished, + the value is 100. + """ + class ExecutionState(proto.Enum): + r"""Types of ScanRun execution state.""" + EXECUTION_STATE_UNSPECIFIED = 0 + QUEUED = 1 + SCANNING = 2 + FINISHED = 3 + + class ResultState(proto.Enum): + r"""Types of ScanRun result state.""" + RESULT_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + ERROR = 2 + KILLED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + execution_state = proto.Field( + proto.ENUM, + number=2, + enum=ExecutionState, + ) + result_state = proto.Field( + proto.ENUM, + number=3, + enum=ResultState, + ) + start_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + urls_crawled_count = proto.Field( + proto.INT64, + number=6, + ) + urls_tested_count = proto.Field( + proto.INT64, + number=7, + ) + has_vulnerabilities = proto.Field( + proto.BOOL, + number=8, + ) + progress_percent = proto.Field( + proto.INT32, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py new file mode 100644 index 0000000..5191f21 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats as gcw_finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1alpha', + manifest={ + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetScanConfigRequest', + 'ListScanConfigsRequest', + 'UpdateScanConfigRequest', + 'ListScanConfigsResponse', + 'StartScanRunRequest', + 'GetScanRunRequest', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StopScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'GetFindingRequest', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + }, +) + + +class CreateScanConfigRequest(proto.Message): + r"""Request for the ``CreateScanConfig`` method. + Attributes: + parent (str): + Required. The parent resource name where the + scan is created, which should be a project + resource name in the format + 'projects/{projectId}'. + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be created. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + scan_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + + +class DeleteScanConfigRequest(proto.Message): + r"""Request for the ``DeleteScanConfig`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be deleted. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanConfigRequest(proto.Message): + r"""Request for the ``GetScanConfig`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanConfigsRequest(proto.Message): + r"""Request for the ``ListScanConfigs`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a project resource name in the format + 'projects/{projectId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanConfigs to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class UpdateScanConfigRequest(proto.Message): + r"""Request for the ``UpdateScanConfigRequest`` method. + Attributes: + scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): + Required. The ScanConfig to be updated. The + name field must be set to identify the resource + to be updated. The values of fields not covered + by the mask will be ignored. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + """ + + scan_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListScanConfigsResponse(proto.Message): + r"""Response for the ``ListScanConfigs`` method. + Attributes: + scan_configs (Sequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig]): + The list of ScanConfigs returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_scan_config.ScanConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class StartScanRunRequest(proto.Message): + r"""Request for the ``StartScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be used. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanRunRequest(proto.Message): + r"""Request for the ``GetScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanRun to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanRunsRequest(proto.Message): + r"""Request for the ``ListScanRuns`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanRuns to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListScanRunsResponse(proto.Message): + r"""Response for the ``ListScanRuns`` method. + Attributes: + scan_runs (Sequence[google.cloud.websecurityscanner_v1alpha.types.ScanRun]): + The list of ScanRuns returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_runs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=scan_run.ScanRun, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class StopScanRunRequest(proto.Message): + r"""Request for the ``StopScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanRun to + be stopped. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCrawledUrlsRequest(proto.Message): + r"""Request for the ``ListCrawledUrls`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of CrawledUrls to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCrawledUrlsResponse(proto.Message): + r"""Response for the ``ListCrawledUrls`` method. + Attributes: + crawled_urls (Sequence[google.cloud.websecurityscanner_v1alpha.types.CrawledUrl]): + The list of CrawledUrls returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + crawled_urls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=crawled_url.CrawledUrl, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFindingRequest(proto.Message): + r"""Request for the ``GetFinding`` method. + Attributes: + name (str): + Required. The resource name of the Finding to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request for the ``ListFindings`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + filter (str): + Required. The filter expression. The expression must be in + the format: . Supported field: 'finding_type'. Supported + operator: '='. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of Findings to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response for the ``ListFindings`` method. + Attributes: + findings (Sequence[google.cloud.websecurityscanner_v1alpha.types.Finding]): + The list of Findings returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + findings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=finding.Finding, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingTypeStatsRequest(proto.Message): + r"""Request for the ``ListFindingTypeStats`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingTypeStatsResponse(proto.Message): + r"""Response for the ``ListFindingTypeStats`` method. + Attributes: + finding_type_stats (Sequence[google.cloud.websecurityscanner_v1alpha.types.FindingTypeStats]): + The list of FindingTypeStats returned. + """ + + finding_type_stats = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_finding_type_stats.FindingTypeStats, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py new file mode 100644 index 0000000..16bdd22 --- /dev/null +++ b/owl-bot-staging/v1alpha/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/websecurityscanner_v1alpha/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py new file mode 100644 index 0000000..5dd19da --- /dev/null +++ b/owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py @@ -0,0 +1,188 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class websecurityscannerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', '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: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=websecurityscannerCallTransformer(), +): + """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 websecurityscanner client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py new file mode 100644 index 0000000..a33245a --- /dev/null +++ b/owl-bot-staging/v1alpha/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-websecurityscanner', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py b/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py new file mode 100644 index 0000000..71916a3 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py @@ -0,0 +1,4934 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerAsyncClient +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import transports +from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.websecurityscanner_v1alpha.types import crawled_url +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import finding_addon +from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats +from google.cloud.websecurityscanner_v1alpha.types import scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import scan_run +from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert WebSecurityScannerClient._get_default_mtls_endpoint(None) is None + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + WebSecurityScannerClient, + WebSecurityScannerAsyncClient, +]) +def test_web_security_scanner_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WebSecurityScannerGrpcTransport, "grpc"), + (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + WebSecurityScannerClient, + WebSecurityScannerAsyncClient, +]) +def test_web_security_scanner_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +def test_web_security_scanner_client_get_transport_class(): + transport = WebSecurityScannerClient.get_transport_class() + available_transports = [ + transports.WebSecurityScannerGrpcTransport, + ] + assert transport in available_transports + + transport = WebSecurityScannerClient.get_transport_class("grpc") + assert transport == transports.WebSecurityScannerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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(WebSecurityScannerClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(WebSecurityScannerClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_web_security_scanner_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_web_security_scanner_client_client_options_from_dict(): + with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebSecurityScannerClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_scan_config(transport: str = 'grpc', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + response = client.create_scan_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] == web_security_scanner.CreateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +def test_create_scan_config_from_dict(): + test_create_scan_config(request_type=dict) + + +def test_create_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + client.create_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest() + + +@pytest.mark.asyncio +async def test_create_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + response = await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.asyncio +async def test_create_scan_config_async_from_dict(): + await test_create_scan_config_async(request_type=dict) + + +def test_create_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.create_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.create_scan_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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') + + +def test_create_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') + + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +def test_delete_scan_config(transport: str = 'grpc', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scan_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] == web_security_scanner.DeleteScanConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_from_dict(): + test_delete_scan_config(request_type=dict) + + +def test_delete_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + client.delete_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_scan_config_async_from_dict(): + await test_delete_scan_config_async(request_type=dict) + + +def test_delete_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +def test_get_scan_config(transport: str = 'grpc', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + response = client.get_scan_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] == web_security_scanner.GetScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +def test_get_scan_config_from_dict(): + test_get_scan_config(request_type=dict) + + +def test_get_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + client.get_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest() + + +@pytest.mark.asyncio +async def test_get_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + response = await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.asyncio +async def test_get_scan_config_async_from_dict(): + await test_get_scan_config_async(request_type=dict) + + +def test_get_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.get_scan_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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +def test_list_scan_configs(transport: str = 'grpc', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_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] == web_security_scanner.ListScanConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_configs_from_dict(): + test_list_scan_configs(request_type=dict) + + +def test_list_scan_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + client.list_scan_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_from_dict(): + await test_list_scan_configs_async(request_type=dict) + + +def test_list_scan_configs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_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_scan_configs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + await client.list_scan_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_scan_configs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_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_scan_configs_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_scan_configs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_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_scan_configs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +def test_list_scan_configs_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_configs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) + for i in results) + +def test_list_scan_configs_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_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_scan_configs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_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, scan_config.ScanConfig) + for i in responses) + +@pytest.mark.asyncio +async def test_list_scan_configs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_scan_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_update_scan_config(transport: str = 'grpc', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + response = client.update_scan_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] == web_security_scanner.UpdateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +def test_update_scan_config_from_dict(): + test_update_scan_config(request_type=dict) + + +def test_update_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + client.update_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest() + + +@pytest.mark.asyncio +async def test_update_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + )) + response = await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + + +@pytest.mark.asyncio +async def test_update_scan_config_async_from_dict(): + await test_update_scan_config_async(request_type=dict) + + +def test_update_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'scan_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.update_scan_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', + 'scan_config.name=scan_config.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'scan_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.update_scan_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', + 'scan_config.name=scan_config.name/value', + ) in kw['metadata'] + + +def test_update_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_start_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_from_dict(): + test_start_scan_run(request_type=dict) + + +def test_start_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + client.start_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + +@pytest.mark.asyncio +async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_start_scan_run_async_from_dict(): + await test_start_scan_run_async(request_type=dict) + + +def test_start_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_start_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_start_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_scan_run( + 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_start_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_start_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_scan_run( + 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_start_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +def test_get_scan_run(transport: str = 'grpc', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_from_dict(): + test_get_scan_run(request_type=dict) + + +def test_get_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + client.get_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + +@pytest.mark.asyncio +async def test_get_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_get_scan_run_async_from_dict(): + await test_get_scan_run_async(request_type=dict) + + +def test_get_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_run( + 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_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_run( + 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_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +def test_list_scan_runs(transport: str = 'grpc', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_runs_from_dict(): + test_list_scan_runs(request_type=dict) + + +def test_list_scan_runs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + client.list_scan_runs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + +@pytest.mark.asyncio +async def test_list_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_from_dict(): + await test_list_scan_runs_async(request_type=dict) + + +def test_list_scan_runs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_scan_runs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_scan_runs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_runs( + 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_scan_runs_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_scan_runs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_runs( + 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_scan_runs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +def test_list_scan_runs_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_runs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) + for i in results) + +def test_list_scan_runs_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_runs(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_scan_runs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_runs(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, scan_run.ScanRun) + for i in responses) + +@pytest.mark.asyncio +async def test_list_scan_runs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_scan_runs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_stop_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_from_dict(): + test_stop_scan_run(request_type=dict) + + +def test_stop_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + client.stop_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + +@pytest.mark.asyncio +async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_stop_scan_run_async_from_dict(): + await test_stop_scan_run_async(request_type=dict) + + +def test_stop_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_stop_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_stop_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_scan_run( + 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_stop_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_stop_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_scan_run( + 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_stop_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +def test_list_crawled_urls(transport: str = 'grpc', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_crawled_urls_from_dict(): + test_list_crawled_urls(request_type=dict) + + +def test_list_crawled_urls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + client.list_crawled_urls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_from_dict(): + await test_list_crawled_urls_async(request_type=dict) + + +def test_list_crawled_urls_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_crawled_urls_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_crawled_urls_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crawled_urls( + 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_crawled_urls_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_crawled_urls_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crawled_urls( + 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_crawled_urls_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +def test_list_crawled_urls_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crawled_urls(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) + for i in results) + +def test_list_crawled_urls_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in responses) + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_crawled_urls(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_finding(transport: str = 'grpc', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + response = client.get_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] == web_security_scanner.GetFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +def test_get_finding_from_dict(): + test_get_finding(request_type=dict) + + +def test_get_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + client.get_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest() + + +@pytest.mark.asyncio +async def test_get_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + response = await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.asyncio +async def test_get_finding_async_from_dict(): + await test_get_finding_async(request_type=dict) + + +def test_get_finding_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_finding_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_finding_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__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.get_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].name == 'name_value' + + +def test_get_finding_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_finding_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__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.get_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].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_finding_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +def test_list_findings(transport: str = 'grpc', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + ) + 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] == web_security_scanner.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' + + +def test_list_findings_from_dict(): + test_list_findings(request_type=dict) + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + 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] == web_security_scanner.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.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 = web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.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', + filter='filter_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].filter == 'filter_value' + + +def test_list_findings_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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', + filter='filter_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].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_findings_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_findings_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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_finding_type_stats(transport: str = 'grpc', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse( + ) + response = client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_from_dict(): + test_list_finding_type_stats(request_type=dict) + + +def test_list_finding_type_stats_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + client.list_finding_type_stats() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + response = await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async_from_dict(): + await test_list_finding_type_stats_async(request_type=dict) + + +def test_list_finding_type_stats_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_finding_type_stats_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_finding_type_stats_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_finding_type_stats( + 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_finding_type_stats_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_finding_type_stats( + 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_finding_type_stats_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_scan_config', + 'delete_scan_config', + 'get_scan_config', + 'list_scan_configs', + 'update_scan_config', + 'start_scan_run', + 'get_scan_run', + 'list_scan_runs', + 'stop_scan_run', + 'list_crawled_urls', + 'get_finding', + 'list_findings', + 'list_finding_type_stats', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + 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_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebSecurityScannerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebSecurityScannerClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebSecurityScannerGrpcTransport, grpc_helpers), + (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_web_security_scanner_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "websecurityscanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_web_security_scanner_host_no_port(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), + ) + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +def test_web_security_scanner_host_with_port(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), + ) + assert client.transport._host == 'websecurityscanner.googleapis.com:8000' + +def test_web_security_scanner_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_web_security_scanner_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_finding_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + finding = "octopus" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "project": "oyster", + "scan_config": "nudibranch", + "scan_run": "cuttlefish", + "finding": "mussel", + } + path = WebSecurityScannerClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_finding_path(path) + assert expected == actual + +def test_scan_config_path(): + project = "winkle" + scan_config = "nautilus" + expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + actual = WebSecurityScannerClient.scan_config_path(project, scan_config) + assert expected == actual + + +def test_parse_scan_config_path(): + expected = { + "project": "scallop", + "scan_config": "abalone", + } + path = WebSecurityScannerClient.scan_config_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_config_path(path) + assert expected == actual + +def test_scan_run_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) + assert expected == actual + + +def test_parse_scan_run_path(): + expected = { + "project": "octopus", + "scan_config": "oyster", + "scan_run": "nudibranch", + } + path = WebSecurityScannerClient.scan_run_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_run_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebSecurityScannerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = WebSecurityScannerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebSecurityScannerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = WebSecurityScannerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebSecurityScannerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = WebSecurityScannerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = WebSecurityScannerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = WebSecurityScannerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = WebSecurityScannerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = WebSecurityScannerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + transport_class = WebSecurityScannerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta/.coveragerc b/owl-bot-staging/v1beta/.coveragerc new file mode 100644 index 0000000..6b433c1 --- /dev/null +++ b/owl-bot-staging/v1beta/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/websecurityscanner/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta/MANIFEST.in b/owl-bot-staging/v1beta/MANIFEST.in new file mode 100644 index 0000000..e23fd8a --- /dev/null +++ b/owl-bot-staging/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/websecurityscanner *.py +recursive-include google/cloud/websecurityscanner_v1beta *.py diff --git a/owl-bot-staging/v1beta/README.rst b/owl-bot-staging/v1beta/README.rst new file mode 100644 index 0000000..4de4c10 --- /dev/null +++ b/owl-bot-staging/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Websecurityscanner API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Websecurityscanner API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta/docs/conf.py b/owl-bot-staging/v1beta/docs/conf.py new file mode 100644 index 0000000..c393cbd --- /dev/null +++ b/owl-bot-staging/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-websecurityscanner documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-websecurityscanner" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-websecurityscanner-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-websecurityscanner.tex", + u"google-cloud-websecurityscanner Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-websecurityscanner", + u"Google Cloud Websecurityscanner Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-websecurityscanner", + u"google-cloud-websecurityscanner Documentation", + author, + "google-cloud-websecurityscanner", + "GAPIC library for Google Cloud Websecurityscanner API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta/docs/index.rst b/owl-bot-staging/v1beta/docs/index.rst new file mode 100644 index 0000000..c5a8dfe --- /dev/null +++ b/owl-bot-staging/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + websecurityscanner_v1beta/services + websecurityscanner_v1beta/types diff --git a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst new file mode 100644 index 0000000..37adbdc --- /dev/null +++ b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Websecurityscanner v1beta API +======================================================= +.. toctree:: + :maxdepth: 2 + + web_security_scanner diff --git a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst new file mode 100644 index 0000000..0a1ff8f --- /dev/null +++ b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Websecurityscanner v1beta API +==================================================== + +.. automodule:: google.cloud.websecurityscanner_v1beta.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst new file mode 100644 index 0000000..8918ace --- /dev/null +++ b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst @@ -0,0 +1,10 @@ +WebSecurityScanner +------------------------------------ + +.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner + :members: + :inherited-members: + +.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py new file mode 100644 index 0000000..0ea05a0 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1beta.services.web_security_scanner.client import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient + +from google.cloud.websecurityscanner_v1beta.types.crawled_url import CrawledUrl +from google.cloud.websecurityscanner_v1beta.types.finding import Finding +from google.cloud.websecurityscanner_v1beta.types.finding_addon import Form +from google.cloud.websecurityscanner_v1beta.types.finding_addon import OutdatedLibrary +from google.cloud.websecurityscanner_v1beta.types.finding_addon import ViolatingResource +from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableHeaders +from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableParameters +from google.cloud.websecurityscanner_v1beta.types.finding_addon import Xss +from google.cloud.websecurityscanner_v1beta.types.finding_type_stats import FindingTypeStats +from google.cloud.websecurityscanner_v1beta.types.scan_config import ScanConfig +from google.cloud.websecurityscanner_v1beta.types.scan_config_error import ScanConfigError +from google.cloud.websecurityscanner_v1beta.types.scan_run import ScanRun +from google.cloud.websecurityscanner_v1beta.types.scan_run_error_trace import ScanRunErrorTrace +from google.cloud.websecurityscanner_v1beta.types.scan_run_warning_trace import ScanRunWarningTrace +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import CreateScanConfigRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import DeleteScanConfigRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetFindingRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanConfigRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanRunRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsResponse +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StartScanRunRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StopScanRunRequest +from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ('WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed new file mode 100644 index 0000000..8cfb5d2 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py new file mode 100644 index 0000000..130eb6c --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.web_security_scanner import WebSecurityScannerClient +from .services.web_security_scanner import WebSecurityScannerAsyncClient + +from .types.crawled_url import CrawledUrl +from .types.finding import Finding +from .types.finding_addon import Form +from .types.finding_addon import OutdatedLibrary +from .types.finding_addon import ViolatingResource +from .types.finding_addon import VulnerableHeaders +from .types.finding_addon import VulnerableParameters +from .types.finding_addon import Xss +from .types.finding_type_stats import FindingTypeStats +from .types.scan_config import ScanConfig +from .types.scan_config_error import ScanConfigError +from .types.scan_run import ScanRun +from .types.scan_run_error_trace import ScanRunErrorTrace +from .types.scan_run_warning_trace import ScanRunWarningTrace +from .types.web_security_scanner import CreateScanConfigRequest +from .types.web_security_scanner import DeleteScanConfigRequest +from .types.web_security_scanner import GetFindingRequest +from .types.web_security_scanner import GetScanConfigRequest +from .types.web_security_scanner import GetScanRunRequest +from .types.web_security_scanner import ListCrawledUrlsRequest +from .types.web_security_scanner import ListCrawledUrlsResponse +from .types.web_security_scanner import ListFindingsRequest +from .types.web_security_scanner import ListFindingsResponse +from .types.web_security_scanner import ListFindingTypeStatsRequest +from .types.web_security_scanner import ListFindingTypeStatsResponse +from .types.web_security_scanner import ListScanConfigsRequest +from .types.web_security_scanner import ListScanConfigsResponse +from .types.web_security_scanner import ListScanRunsRequest +from .types.web_security_scanner import ListScanRunsResponse +from .types.web_security_scanner import StartScanRunRequest +from .types.web_security_scanner import StopScanRunRequest +from .types.web_security_scanner import UpdateScanConfigRequest + +__all__ = ( + 'WebSecurityScannerAsyncClient', +'CrawledUrl', +'CreateScanConfigRequest', +'DeleteScanConfigRequest', +'Finding', +'FindingTypeStats', +'Form', +'GetFindingRequest', +'GetScanConfigRequest', +'GetScanRunRequest', +'ListCrawledUrlsRequest', +'ListCrawledUrlsResponse', +'ListFindingTypeStatsRequest', +'ListFindingTypeStatsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListScanConfigsRequest', +'ListScanConfigsResponse', +'ListScanRunsRequest', +'ListScanRunsResponse', +'OutdatedLibrary', +'ScanConfig', +'ScanConfigError', +'ScanRun', +'ScanRunErrorTrace', +'ScanRunWarningTrace', +'StartScanRunRequest', +'StopScanRunRequest', +'UpdateScanConfigRequest', +'ViolatingResource', +'VulnerableHeaders', +'VulnerableParameters', +'WebSecurityScannerClient', +'Xss', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json new file mode 100644 index 0000000..114e6f0 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json @@ -0,0 +1,153 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.websecurityscanner_v1beta", + "protoPackage": "google.cloud.websecurityscanner.v1beta", + "schema": "1.0", + "services": { + "WebSecurityScanner": { + "clients": { + "grpc": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebSecurityScannerAsyncClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed new file mode 100644 index 0000000..8cfb5d2 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py new file mode 100644 index 0000000..46b053b --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import WebSecurityScannerClient +from .async_client import WebSecurityScannerAsyncClient + +__all__ = ( + 'WebSecurityScannerClient', + 'WebSecurityScannerAsyncClient', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py new file mode 100644 index 0000000..8942159 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py @@ -0,0 +1,1316 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_addon +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .client import WebSecurityScannerClient + + +class WebSecurityScannerAsyncClient: + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + _client: WebSecurityScannerClient + + DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT + + finding_path = staticmethod(WebSecurityScannerClient.finding_path) + parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) + scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) + parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) + scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) + parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) + common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) + parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) + common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) + parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) + common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) + parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) + common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) + parse_common_location_path = staticmethod(WebSecurityScannerClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerAsyncClient: The constructed client. + """ + return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WebSecurityScannerClient).get_transport_class, type(WebSecurityScannerClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, WebSecurityScannerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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, ~.WebSecurityScannerTransport]): 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 = WebSecurityScannerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_scan_config(self, + request: web_security_scanner.CreateScanConfigRequest = None, + *, + parent: str = None, + scan_config: gcw_scan_config.ScanConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest`): + The request object. Request for the `CreateScanConfig` + method. + parent (:class:`str`): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, scan_config]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.CreateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_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_scan_config, + default_timeout=600.0, + client_info=DEFAULT_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_scan_config(self, + request: web_security_scanner.DeleteScanConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest`): + The request object. Request for the `DeleteScanConfig` + method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.DeleteScanConfigRequest(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_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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_scan_config(self, + request: web_security_scanner.GetScanConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest`): + The request object. Request for the `GetScanConfig` + method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.GetScanConfigRequest(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_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_scan_configs(self, + request: web_security_scanner.ListScanConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsAsyncPager: + r"""Lists ScanConfigs under a given project. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest`): + The request object. Request for the `ListScanConfigs` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: + Response for the ListScanConfigs method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListScanConfigsRequest(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_scan_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListScanConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scan_config(self, + request: web_security_scanner.UpdateScanConfigRequest = None, + *, + scan_config: gcw_scan_config.ScanConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest`): + The request object. Request for the + `UpdateScanConfigRequest` method. + scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.UpdateScanConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_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_scan_config, + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def start_scan_run(self, + request: web_security_scanner.StartScanRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest`): + The request object. Request for the `StartScanRun` + method. + name (:class:`str`): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.StartScanRunRequest(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.start_scan_run, + default_timeout=600.0, + client_info=DEFAULT_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_scan_run(self, + request: web_security_scanner.GetScanRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest`): + The request object. Request for the `GetScanRun` method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.GetScanRunRequest(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_scan_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_scan_runs(self, + request: web_security_scanner.ListScanRunsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsAsyncPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest`): + The request object. Request for the `ListScanRuns` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsAsyncPager: + Response for the ListScanRuns method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListScanRunsRequest(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_scan_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListScanRunsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_scan_run(self, + request: web_security_scanner.StopScanRunRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest`): + The request object. Request for the `StopScanRun` + method. + name (:class:`str`): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.StopScanRunRequest(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.stop_scan_run, + default_timeout=600.0, + client_info=DEFAULT_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 list_crawled_urls(self, + request: web_security_scanner.ListCrawledUrlsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsAsyncPager: + r"""List CrawledUrls under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest`): + The request object. Request for the `ListCrawledUrls` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: + Response for the ListCrawledUrls method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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.ListCrawledUrlsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_finding(self, + request: web_security_scanner.GetFindingRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.GetFindingRequest`): + The request object. Request for the `GetFinding` method. + name (:class:`str`): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.GetFindingRequest(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_finding, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 list_findings(self, + request: web_security_scanner.ListFindingsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""List Findings under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest`): + The request object. Request for the `ListFindings` + method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsAsyncPager: + Response for the ListFindings method. + + 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, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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_finding_type_stats(self, + request: web_security_scanner.ListFindingTypeStatsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + Args: + request (:class:`google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest`): + The request object. Request for the + `ListFindingTypeStats` method. + parent (:class:`str`): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats 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([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-websecurityscanner", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebSecurityScannerAsyncClient", +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py new file mode 100644 index 0000000..6beadac --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py @@ -0,0 +1,1462 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_addon +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebSecurityScannerGrpcTransport +from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport + + +class WebSecurityScannerClientMeta(type): + """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] + _transport_registry["grpc"] = WebSecurityScannerGrpcTransport + _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[WebSecurityScannerTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): + """Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "websecurityscanner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebSecurityScannerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebSecurityScannerTransport: + """Returns the transport used by the client instance. + + Returns: + WebSecurityScannerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_config_path(project: str,scan_config: str,) -> str: + """Returns a fully-qualified scan_config string.""" + return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + + @staticmethod + def parse_scan_config_path(path: str) -> Dict[str,str]: + """Parses a scan_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: + """Returns a fully-qualified scan_run string.""" + return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + + @staticmethod + def parse_scan_run_path(path: str) -> Dict[str,str]: + """Parses a scan_run path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, WebSecurityScannerTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the web security scanner 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, WebSecurityScannerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, WebSecurityScannerTransport): + # transport is a WebSecurityScannerTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_scan_config(self, + request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, + *, + parent: str = None, + scan_config: gcw_scan_config.ScanConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Creates a new ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]): + The request object. Request for the `CreateScanConfig` + method. + parent (str): + Required. The parent resource name + where the scan is created, which should + be a project resource name in the format + 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be + created. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, scan_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 web_security_scanner.CreateScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.CreateScanConfigRequest): + request = web_security_scanner.CreateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scan_config is not None: + request.scan_config = scan_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scan_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_scan_config(self, + request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing ScanConfig and its child + resources. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]): + The request object. Request for the `DeleteScanConfig` + method. + name (str): + Required. The resource name of the + ScanConfig to be deleted. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + 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 web_security_scanner.DeleteScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.DeleteScanConfigRequest): + request = web_security_scanner.DeleteScanConfigRequest(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_scan_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_scan_config(self, + request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Gets a ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]): + The request object. Request for the `GetScanConfig` + method. + name (str): + Required. The resource name of the + ScanConfig to be returned. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.GetScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetScanConfigRequest): + request = web_security_scanner.GetScanConfigRequest(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_scan_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 list_scan_configs(self, + request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanConfigsPager: + r"""Lists ScanConfigs under a given project. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]): + The request object. Request for the `ListScanConfigs` + method. + parent (str): + Required. The parent resource name, + which should be a project resource name + in the format 'projects/{projectId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsPager: + Response for the ListScanConfigs method. + + 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 web_security_scanner.ListScanConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListScanConfigsRequest): + request = web_security_scanner.ListScanConfigsRequest(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_scan_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.ListScanConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scan_config(self, + request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, + *, + scan_config: gcw_scan_config.ScanConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]): + The request object. Request for the + `UpdateScanConfigRequest` method. + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be + updated. The name field must be set to + identify the resource to be updated. The + values of fields not covered by the mask + will be ignored. + + This corresponds to the ``scan_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For + the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scan_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 web_security_scanner.UpdateScanConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.UpdateScanConfigRequest): + request = web_security_scanner.UpdateScanConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scan_config is not None: + request.scan_config = scan_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_scan_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scan_config.name", request.scan_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def start_scan_run(self, + request: Union[web_security_scanner.StartScanRunRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Start a ScanRun according to the given ScanConfig. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]): + The request object. Request for the `StartScanRun` + method. + name (str): + Required. The resource name of the + ScanConfig to be used. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.StartScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.StartScanRunRequest): + request = web_security_scanner.StartScanRunRequest(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.start_scan_run] + + # 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_scan_run(self, + request: Union[web_security_scanner.GetScanRunRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Gets a ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]): + The request object. Request for the `GetScanRun` method. + name (str): + Required. The resource name of the + ScanRun to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.GetScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetScanRunRequest): + request = web_security_scanner.GetScanRunRequest(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_scan_run] + + # 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 list_scan_runs(self, + request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListScanRunsPager: + r"""Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]): + The request object. Request for the `ListScanRuns` + method. + parent (str): + Required. The parent resource name, + which should be a scan resource name in + the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsPager: + Response for the ListScanRuns method. + + 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 web_security_scanner.ListScanRunsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListScanRunsRequest): + request = web_security_scanner.ListScanRunsRequest(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_scan_runs] + + # 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.ListScanRunsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_scan_run(self, + request: Union[web_security_scanner.StopScanRunRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Stops a ScanRun. The stopped ScanRun is returned. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]): + The request object. Request for the `StopScanRun` + method. + name (str): + Required. The resource name of the + ScanRun to be stopped. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.StopScanRunRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.StopScanRunRequest): + request = web_security_scanner.StopScanRunRequest(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.stop_scan_run] + + # 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 list_crawled_urls(self, + request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCrawledUrlsPager: + r"""List CrawledUrls under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]): + The request object. Request for the `ListCrawledUrls` + method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsPager: + Response for the ListCrawledUrls method. + + 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 web_security_scanner.ListCrawledUrlsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListCrawledUrlsRequest): + request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] + + # 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.ListCrawledUrlsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_finding(self, + request: Union[web_security_scanner.GetFindingRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Gets a Finding. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]): + The request object. Request for the `GetFinding` method. + name (str): + Required. The resource name of the + Finding to be returned. The name follows + the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 web_security_scanner.GetFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.GetFindingRequest): + request = web_security_scanner.GetFindingRequest(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_finding] + + # 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 list_findings(self, + request: Union[web_security_scanner.ListFindingsRequest, dict] = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""List Findings under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]): + The request object. Request for the `ListFindings` + method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Required. The filter expression. The expression must be + in the format: . Supported field: 'finding_type'. + Supported operator: '='. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsPager: + Response for the ListFindings method. + + 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, filter]) + if request is 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 web_security_scanner.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListFindingsRequest): + request = web_security_scanner.ListFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_finding_type_stats(self, + request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""List all FindingTypeStats under a given ScanRun. + + Args: + request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]): + The request object. Request for the + `ListFindingTypeStats` method. + parent (str): + Required. The parent resource name, + which should be a scan run resource name + in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: + Response for the ListFindingTypeStats 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([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 web_security_scanner.ListFindingTypeStatsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, web_security_scanner.ListFindingTypeStatsRequest): + request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] + + # 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-websecurityscanner", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebSecurityScannerClient", +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py new file mode 100644 index 0000000..61ca2bf --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner + + +class ListScanConfigsPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` + 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[..., web_security_scanner.ListScanConfigsResponse], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): + 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 = web_security_scanner.ListScanConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + for page in self.pages: + yield from page.scan_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanConfigsAsyncPager: + """A pager for iterating through ``list_scan_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanConfigs`` requests and continue to iterate + through the ``scan_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` + 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[web_security_scanner.ListScanConfigsResponse]], + request: web_security_scanner.ListScanConfigsRequest, + response: web_security_scanner.ListScanConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): + 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 = web_security_scanner.ListScanConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListScanConfigsResponse]: + 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[scan_config.ScanConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` + 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[..., web_security_scanner.ListScanRunsResponse], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): + 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 = web_security_scanner.ListScanRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + for page in self.pages: + yield from page.scan_runs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListScanRunsAsyncPager: + """A pager for iterating through ``list_scan_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scan_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScanRuns`` requests and continue to iterate + through the ``scan_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` + 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[web_security_scanner.ListScanRunsResponse]], + request: web_security_scanner.ListScanRunsRequest, + response: web_security_scanner.ListScanRunsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): + 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 = web_security_scanner.ListScanRunsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListScanRunsResponse]: + 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[scan_run.ScanRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scan_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` + 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[..., web_security_scanner.ListCrawledUrlsResponse], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): + 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 = web_security_scanner.ListCrawledUrlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + for page in self.pages: + yield from page.crawled_urls + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCrawledUrlsAsyncPager: + """A pager for iterating through ``list_crawled_urls`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crawled_urls`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCrawledUrls`` requests and continue to iterate + through the ``crawled_urls`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` + 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[web_security_scanner.ListCrawledUrlsResponse]], + request: web_security_scanner.ListCrawledUrlsRequest, + response: web_security_scanner.ListCrawledUrlsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): + 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 = web_security_scanner.ListCrawledUrlsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[web_security_scanner.ListCrawledUrlsResponse]: + 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[crawled_url.CrawledUrl]: + async def async_generator(): + async for page in self.pages: + for response in page.crawled_urls: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., web_security_scanner.ListFindingsResponse], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[web_security_scanner.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[web_security_scanner.ListFindingsResponse]], + request: web_security_scanner.ListFindingsRequest, + response: web_security_scanner.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): + The initial request object. + response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = web_security_scanner.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[web_security_scanner.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) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py new file mode 100644 index 0000000..19f4df5 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import WebSecurityScannerTransport +from .grpc import WebSecurityScannerGrpcTransport +from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] +_transport_registry['grpc'] = WebSecurityScannerGrpcTransport +_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport + +__all__ = ( + 'WebSecurityScannerTransport', + 'WebSecurityScannerGrpcTransport', + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py new file mode 100644 index 0000000..b9d0a1c --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py @@ -0,0 +1,404 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-websecurityscanner', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class WebSecurityScannerTransport(abc.ABC): + """Abstract transport class for WebSecurityScanner.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'websecurityscanner.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_scan_config: gapic_v1.method.wrap_method( + self.create_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.delete_scan_config: gapic_v1.method.wrap_method( + self.delete_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_config: gapic_v1.method.wrap_method( + self.get_scan_config, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_configs: gapic_v1.method.wrap_method( + self.list_scan_configs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_scan_config: gapic_v1.method.wrap_method( + self.update_scan_config, + default_timeout=600.0, + client_info=client_info, + ), + self.start_scan_run: gapic_v1.method.wrap_method( + self.start_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.get_scan_run: gapic_v1.method.wrap_method( + self.get_scan_run, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_scan_runs: gapic_v1.method.wrap_method( + self.list_scan_runs, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.stop_scan_run: gapic_v1.method.wrap_method( + self.stop_scan_run, + default_timeout=600.0, + client_info=client_info, + ), + self.list_crawled_urls: gapic_v1.method.wrap_method( + self.list_crawled_urls, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_finding: gapic_v1.method.wrap_method( + self.get_finding, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_finding_type_stats: gapic_v1.method.wrap_method( + self.list_finding_type_stats, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Union[ + scan_config.ScanConfig, + Awaitable[scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Union[ + web_security_scanner.ListScanConfigsResponse, + Awaitable[web_security_scanner.ListScanConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Union[ + gcw_scan_config.ScanConfig, + Awaitable[gcw_scan_config.ScanConfig] + ]]: + raise NotImplementedError() + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Union[ + web_security_scanner.ListScanRunsResponse, + Awaitable[web_security_scanner.ListScanRunsResponse] + ]]: + raise NotImplementedError() + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Union[ + scan_run.ScanRun, + Awaitable[scan_run.ScanRun] + ]]: + raise NotImplementedError() + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Union[ + web_security_scanner.ListCrawledUrlsResponse, + Awaitable[web_security_scanner.ListCrawledUrlsResponse] + ]]: + raise NotImplementedError() + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Union[ + web_security_scanner.ListFindingsResponse, + Awaitable[web_security_scanner.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Union[ + web_security_scanner.ListFindingTypeStatsResponse, + Awaitable[web_security_scanner.ListFindingTypeStatsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'WebSecurityScannerTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py new file mode 100644 index 0000000..b2bb084 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO + + +class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): + """gRPC backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + 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 = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + ~.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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + scan_config.ScanConfig]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + ~.ListScanConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + gcw_scan_config.ScanConfig]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + ~.ScanConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + ~.ListScanRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + scan_run.ScanRun]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + ~.ScanRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + ~.ListCrawledUrlsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + finding.Finding]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + ~.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 'get_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + 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.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + ~.ListFindingTypeStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + +__all__ = ( + 'WebSecurityScannerGrpcTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py new file mode 100644 index 0000000..d9d49d3 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py @@ -0,0 +1,579 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.protobuf import empty_pb2 # type: ignore +from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO +from .grpc import WebSecurityScannerGrpcTransport + + +class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): + """gRPC AsyncIO backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + 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 = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'websecurityscanner.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_scan_config(self) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the create scan config method over gRPC. + + Creates a new ScanConfig. + + Returns: + Callable[[~.CreateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', + request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['create_scan_config'] + + @property + def delete_scan_config(self) -> Callable[ + [web_security_scanner.DeleteScanConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete scan config method over gRPC. + + Deletes an existing ScanConfig and its child + resources. + + Returns: + Callable[[~.DeleteScanConfigRequest], + 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_scan_config' not in self._stubs: + self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', + request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_scan_config'] + + @property + def get_scan_config(self) -> Callable[ + [web_security_scanner.GetScanConfigRequest], + Awaitable[scan_config.ScanConfig]]: + r"""Return a callable for the get scan config method over gRPC. + + Gets a ScanConfig. + + Returns: + Callable[[~.GetScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', + request_serializer=web_security_scanner.GetScanConfigRequest.serialize, + response_deserializer=scan_config.ScanConfig.deserialize, + ) + return self._stubs['get_scan_config'] + + @property + def list_scan_configs(self) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + Awaitable[web_security_scanner.ListScanConfigsResponse]]: + r"""Return a callable for the list scan configs method over gRPC. + + Lists ScanConfigs under a given project. + + Returns: + Callable[[~.ListScanConfigsRequest], + Awaitable[~.ListScanConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: + self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', + request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, + response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, + ) + return self._stubs['list_scan_configs'] + + @property + def update_scan_config(self) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], + Awaitable[gcw_scan_config.ScanConfig]]: + r"""Return a callable for the update scan config method over gRPC. + + Updates a ScanConfig. This method support partial + update of a ScanConfig. + + Returns: + Callable[[~.UpdateScanConfigRequest], + Awaitable[~.ScanConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_config' not in self._stubs: + self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', + request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, + response_deserializer=gcw_scan_config.ScanConfig.deserialize, + ) + return self._stubs['update_scan_config'] + + @property + def start_scan_run(self) -> Callable[ + [web_security_scanner.StartScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the start scan run method over gRPC. + + Start a ScanRun according to the given ScanConfig. + + Returns: + Callable[[~.StartScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_scan_run' not in self._stubs: + self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', + request_serializer=web_security_scanner.StartScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['start_scan_run'] + + @property + def get_scan_run(self) -> Callable[ + [web_security_scanner.GetScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the get scan run method over gRPC. + + Gets a ScanRun. + + Returns: + Callable[[~.GetScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_run' not in self._stubs: + self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', + request_serializer=web_security_scanner.GetScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['get_scan_run'] + + @property + def list_scan_runs(self) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + Awaitable[web_security_scanner.ListScanRunsResponse]]: + r"""Return a callable for the list scan runs method over gRPC. + + Lists ScanRuns under a given ScanConfig, in + descending order of ScanRun stop time. + + Returns: + Callable[[~.ListScanRunsRequest], + Awaitable[~.ListScanRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: + self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', + request_serializer=web_security_scanner.ListScanRunsRequest.serialize, + response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, + ) + return self._stubs['list_scan_runs'] + + @property + def stop_scan_run(self) -> Callable[ + [web_security_scanner.StopScanRunRequest], + Awaitable[scan_run.ScanRun]]: + r"""Return a callable for the stop scan run method over gRPC. + + Stops a ScanRun. The stopped ScanRun is returned. + + Returns: + Callable[[~.StopScanRunRequest], + Awaitable[~.ScanRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_scan_run' not in self._stubs: + self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', + request_serializer=web_security_scanner.StopScanRunRequest.serialize, + response_deserializer=scan_run.ScanRun.deserialize, + ) + return self._stubs['stop_scan_run'] + + @property + def list_crawled_urls(self) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: + r"""Return a callable for the list crawled urls method over gRPC. + + List CrawledUrls under a given ScanRun. + + Returns: + Callable[[~.ListCrawledUrlsRequest], + Awaitable[~.ListCrawledUrlsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: + self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', + request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, + response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, + ) + return self._stubs['list_crawled_urls'] + + @property + def get_finding(self) -> Callable[ + [web_security_scanner.GetFindingRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the get finding method over gRPC. + + Gets a Finding. + + Returns: + Callable[[~.GetFindingRequest], + 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 'get_finding' not in self._stubs: + self._stubs['get_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', + request_serializer=web_security_scanner.GetFindingRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['get_finding'] + + @property + def list_findings(self) -> Callable[ + [web_security_scanner.ListFindingsRequest], + Awaitable[web_security_scanner.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + List Findings under a given ScanRun. + + 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.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', + request_serializer=web_security_scanner.ListFindingsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_finding_type_stats(self) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: + r"""Return a callable for the list finding type stats method over gRPC. + + List all FindingTypeStats under a given ScanRun. + + Returns: + Callable[[~.ListFindingTypeStatsRequest], + Awaitable[~.ListFindingTypeStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: + self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( + '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', + request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, + response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, + ) + return self._stubs['list_finding_type_stats'] + + +__all__ = ( + 'WebSecurityScannerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py new file mode 100644 index 0000000..36cb2b7 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .crawled_url import ( + CrawledUrl, +) +from .finding import ( + Finding, +) +from .finding_addon import ( + Form, + OutdatedLibrary, + ViolatingResource, + VulnerableHeaders, + VulnerableParameters, + Xss, +) +from .finding_type_stats import ( + FindingTypeStats, +) +from .scan_config import ( + ScanConfig, +) +from .scan_config_error import ( + ScanConfigError, +) +from .scan_run import ( + ScanRun, +) +from .scan_run_error_trace import ( + ScanRunErrorTrace, +) +from .scan_run_warning_trace import ( + ScanRunWarningTrace, +) +from .web_security_scanner import ( + CreateScanConfigRequest, + DeleteScanConfigRequest, + GetFindingRequest, + GetScanConfigRequest, + GetScanRunRequest, + ListCrawledUrlsRequest, + ListCrawledUrlsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListFindingTypeStatsRequest, + ListFindingTypeStatsResponse, + ListScanConfigsRequest, + ListScanConfigsResponse, + ListScanRunsRequest, + ListScanRunsResponse, + StartScanRunRequest, + StopScanRunRequest, + UpdateScanConfigRequest, +) + +__all__ = ( + 'CrawledUrl', + 'Finding', + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableHeaders', + 'VulnerableParameters', + 'Xss', + 'FindingTypeStats', + 'ScanConfig', + 'ScanConfigError', + 'ScanRun', + 'ScanRunErrorTrace', + 'ScanRunWarningTrace', + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetFindingRequest', + 'GetScanConfigRequest', + 'GetScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + 'ListScanConfigsRequest', + 'ListScanConfigsResponse', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StartScanRunRequest', + 'StopScanRunRequest', + 'UpdateScanConfigRequest', +) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py new file mode 100644 index 0000000..217dcf9 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1beta', + manifest={ + 'CrawledUrl', + }, +) + + +class CrawledUrl(proto.Message): + r"""A CrawledUrl resource represents a URL that was crawled + during a ScanRun. Web Security Scanner Service crawls the web + applications, following all links within the scope of sites, to + find the URLs to test against. + + Attributes: + http_method (str): + The http method of the request that was used + to visit the URL, in uppercase. + url (str): + The URL that was crawled. + body (str): + The body of the request that was used to + visit the URL. + """ + + http_method = proto.Field( + proto.STRING, + number=1, + ) + url = proto.Field( + proto.STRING, + number=2, + ) + body = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py new file mode 100644 index 0000000..273aa54 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1beta.types import finding_addon + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""A Finding resource represents a vulnerability instance + identified during a ScanRun. + + Attributes: + name (str): + The resource name of the Finding. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. + The finding IDs are generated by the system. + finding_type (str): + The type of the Finding. + Detailed and up-to-date information on findings + can be found here: + https://cloud.google.com/security- + scanner/docs/scan-result-details + http_method (str): + The http method of the request that triggered + the vulnerability, in uppercase. + fuzzed_url (str): + The URL produced by the server-side fuzzer + and used in the request that triggered the + vulnerability. + body (str): + The body of the request that triggered the + vulnerability. + description (str): + The description of the vulnerability. + reproduction_url (str): + The URL containing human-readable payload + that user can leverage to reproduce the + vulnerability. + frame_url (str): + If the vulnerability was originated from + nested IFrame, the immediate parent IFrame is + reported. + final_url (str): + The URL where the browser lands when the + vulnerability is detected. + tracking_id (str): + The tracking ID uniquely identifies a + vulnerability instance across multiple ScanRuns. + form (google.cloud.websecurityscanner_v1beta.types.Form): + An addon containing information reported for + a vulnerability with an HTML form, if any. + outdated_library (google.cloud.websecurityscanner_v1beta.types.OutdatedLibrary): + An addon containing information about + outdated libraries. + violating_resource (google.cloud.websecurityscanner_v1beta.types.ViolatingResource): + An addon containing detailed information + regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, + etc. + vulnerable_headers (google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders): + An addon containing information about + vulnerable or missing HTTP headers. + vulnerable_parameters (google.cloud.websecurityscanner_v1beta.types.VulnerableParameters): + An addon containing information about request + parameters which were found to be vulnerable. + xss (google.cloud.websecurityscanner_v1beta.types.Xss): + An addon containing information reported for + an XSS, if any. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + finding_type = proto.Field( + proto.STRING, + number=2, + ) + http_method = proto.Field( + proto.STRING, + number=3, + ) + fuzzed_url = proto.Field( + proto.STRING, + number=4, + ) + body = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + reproduction_url = proto.Field( + proto.STRING, + number=7, + ) + frame_url = proto.Field( + proto.STRING, + number=8, + ) + final_url = proto.Field( + proto.STRING, + number=9, + ) + tracking_id = proto.Field( + proto.STRING, + number=10, + ) + form = proto.Field( + proto.MESSAGE, + number=16, + message=finding_addon.Form, + ) + outdated_library = proto.Field( + proto.MESSAGE, + number=11, + message=finding_addon.OutdatedLibrary, + ) + violating_resource = proto.Field( + proto.MESSAGE, + number=12, + message=finding_addon.ViolatingResource, + ) + vulnerable_headers = proto.Field( + proto.MESSAGE, + number=15, + message=finding_addon.VulnerableHeaders, + ) + vulnerable_parameters = proto.Field( + proto.MESSAGE, + number=13, + message=finding_addon.VulnerableParameters, + ) + xss = proto.Field( + proto.MESSAGE, + number=14, + message=finding_addon.Xss, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py new file mode 100644 index 0000000..98f3b7a --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1beta', + manifest={ + 'Form', + 'OutdatedLibrary', + 'ViolatingResource', + 'VulnerableParameters', + 'VulnerableHeaders', + 'Xss', + }, +) + + +class Form(proto.Message): + r"""! Information about a vulnerability with an HTML. + Attributes: + action_uri (str): + ! The URI where to send the form when it's + submitted. + fields (Sequence[str]): + ! The names of form fields related to the + vulnerability. + """ + + action_uri = proto.Field( + proto.STRING, + number=1, + ) + fields = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class OutdatedLibrary(proto.Message): + r"""Information reported for an outdated library. + Attributes: + library_name (str): + The name of the outdated library. + version (str): + The version number. + learn_more_urls (Sequence[str]): + URLs to learn more information about the + vulnerabilities in the library. + """ + + library_name = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + learn_more_urls = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ViolatingResource(proto.Message): + r"""Information regarding any resource causing the vulnerability + such as JavaScript sources, image, audio files, etc. + + Attributes: + content_type (str): + The MIME type of this resource. + resource_url (str): + URL of this violating resource. + """ + + content_type = proto.Field( + proto.STRING, + number=1, + ) + resource_url = proto.Field( + proto.STRING, + number=2, + ) + + +class VulnerableParameters(proto.Message): + r"""Information about vulnerable request parameters. + Attributes: + parameter_names (Sequence[str]): + The vulnerable parameter names. + """ + + parameter_names = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VulnerableHeaders(proto.Message): + r"""Information about vulnerable or missing HTTP Headers. + Attributes: + headers (Sequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): + List of vulnerable headers. + missing_headers (Sequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): + List of missing headers. + """ + + class Header(proto.Message): + r"""Describes a HTTP Header. + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.STRING, + number=2, + ) + + headers = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Header, + ) + missing_headers = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Header, + ) + + +class Xss(proto.Message): + r"""Information reported for an XSS. + Attributes: + stack_traces (Sequence[str]): + Stack traces leading to the point where the + XSS occurred. + error_message (str): + An error message generated by a javascript + breakage. + """ + + stack_traces = proto.RepeatedField( + proto.STRING, + number=1, + ) + error_message = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py new file mode 100644 index 0000000..35d888f --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1beta', + manifest={ + 'FindingTypeStats', + }, +) + + +class FindingTypeStats(proto.Message): + r"""A FindingTypeStats resource represents stats regarding a + specific FindingType of Findings under a given ScanRun. + + Attributes: + finding_type (str): + The finding type associated with the stats. + finding_count (int): + The count of findings belonging to this + finding type. + """ + + finding_type = proto.Field( + proto.STRING, + number=1, + ) + finding_count = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py new file mode 100644 index 0000000..1b033dc --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1beta.types import scan_run +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanConfig', + }, +) + + +class ScanConfig(proto.Message): + r"""A ScanConfig resource contains the configurations to launch a + scan. + + Attributes: + name (str): + The resource name of the ScanConfig. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + The ScanConfig IDs are generated by the system. + display_name (str): + Required. The user provided display name of + the ScanConfig. + max_qps (int): + The maximum QPS during scanning. A valid value ranges from 5 + to 20 inclusively. If the field is unspecified or its value + is set 0, server will default to 15. Other values outside of + [5, 20] range will be rejected with INVALID_ARGUMENT error. + starting_urls (Sequence[str]): + Required. The starting URLs from which the + scanner finds site pages. + authentication (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication): + The authentication configuration. If + specified, service will use the authentication + configuration during scanning. + user_agent (google.cloud.websecurityscanner_v1beta.types.ScanConfig.UserAgent): + The user agent used during scanning. + blacklist_patterns (Sequence[str]): + The blacklist URL patterns as described in + https://cloud.google.com/security- + scanner/docs/excluded-urls + schedule (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Schedule): + The schedule of the ScanConfig. + target_platforms (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig.TargetPlatform]): + Set of Cloud Platforms targeted by the scan. If empty, + APP_ENGINE will be used as a default. + export_to_security_command_center (google.cloud.websecurityscanner_v1beta.types.ScanConfig.ExportToSecurityCommandCenter): + Controls export of scan configurations and + results to Cloud Security Command Center. + latest_run (google.cloud.websecurityscanner_v1beta.types.ScanRun): + Latest ScanRun if available. + risk_level (google.cloud.websecurityscanner_v1beta.types.ScanConfig.RiskLevel): + The risk level selected for the scan + """ + class UserAgent(proto.Enum): + r"""Type of user agents used for scanning.""" + USER_AGENT_UNSPECIFIED = 0 + CHROME_LINUX = 1 + CHROME_ANDROID = 2 + SAFARI_IPHONE = 3 + + class TargetPlatform(proto.Enum): + r"""Cloud platforms supported by Cloud Web Security Scanner.""" + TARGET_PLATFORM_UNSPECIFIED = 0 + APP_ENGINE = 1 + COMPUTE = 2 + + class RiskLevel(proto.Enum): + r"""Scan risk levels supported by Cloud Web Security Scanner. LOW + impact scanning will minimize requests with the potential to + modify data. To achieve the maximum scan coverage, NORMAL risk + level is recommended. + """ + RISK_LEVEL_UNSPECIFIED = 0 + NORMAL = 1 + LOW = 2 + + class ExportToSecurityCommandCenter(proto.Enum): + r"""Controls export of scan configurations and results to Cloud + Security Command Center. + """ + EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + class Authentication(proto.Message): + r"""Scan authentication configuration. + Attributes: + google_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.GoogleAccount): + Authentication using a Google account. + custom_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.CustomAccount): + Authentication using a custom account. + """ + + class GoogleAccount(proto.Message): + r"""Describes authentication configuration that uses a Google + account. + + Attributes: + username (str): + Required. The user name of the Google + account. + password (str): + Required. Input only. The password of the + Google account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + """ + + username = proto.Field( + proto.STRING, + number=1, + ) + password = proto.Field( + proto.STRING, + number=2, + ) + + class CustomAccount(proto.Message): + r"""Describes authentication configuration that uses a custom + account. + + Attributes: + username (str): + Required. The user name of the custom + account. + password (str): + Required. Input only. The password of the + custom account. The credential is stored + encrypted and not returned in any response nor + included in audit logs. + login_url (str): + Required. The login form URL of the website. + """ + + username = proto.Field( + proto.STRING, + number=1, + ) + password = proto.Field( + proto.STRING, + number=2, + ) + login_url = proto.Field( + proto.STRING, + number=3, + ) + + google_account = proto.Field( + proto.MESSAGE, + number=1, + oneof='authentication', + message='ScanConfig.Authentication.GoogleAccount', + ) + custom_account = proto.Field( + proto.MESSAGE, + number=2, + oneof='authentication', + message='ScanConfig.Authentication.CustomAccount', + ) + + class Schedule(proto.Message): + r"""Scan schedule configuration. + Attributes: + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + A timestamp indicates when the next run will + be scheduled. The value is refreshed by the + server after each run. If unspecified, it will + default to current server time, which means the + scan will be scheduled to start immediately. + interval_duration_days (int): + Required. The duration of time between + executions in days. + """ + + schedule_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + interval_duration_days = proto.Field( + proto.INT32, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + max_qps = proto.Field( + proto.INT32, + number=3, + ) + starting_urls = proto.RepeatedField( + proto.STRING, + number=4, + ) + authentication = proto.Field( + proto.MESSAGE, + number=5, + message=Authentication, + ) + user_agent = proto.Field( + proto.ENUM, + number=6, + enum=UserAgent, + ) + blacklist_patterns = proto.RepeatedField( + proto.STRING, + number=7, + ) + schedule = proto.Field( + proto.MESSAGE, + number=8, + message=Schedule, + ) + target_platforms = proto.RepeatedField( + proto.ENUM, + number=9, + enum=TargetPlatform, + ) + export_to_security_command_center = proto.Field( + proto.ENUM, + number=10, + enum=ExportToSecurityCommandCenter, + ) + latest_run = proto.Field( + proto.MESSAGE, + number=11, + message=scan_run.ScanRun, + ) + risk_level = proto.Field( + proto.ENUM, + number=12, + enum=RiskLevel, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py new file mode 100644 index 0000000..af14d7c --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner.v1beta', + manifest={ + 'ScanConfigError', + }, +) + + +class ScanConfigError(proto.Message): + r"""Defines a custom error message used by CreateScanConfig and + UpdateScanConfig APIs when scan configuration validation fails. + It is also reported as part of a ScanRunErrorTrace message if + scan validation fails due to a scan configuration error. + + Attributes: + code (google.cloud.websecurityscanner_v1beta.types.ScanConfigError.Code): + Indicates the reason code for a configuration + failure. + field_name (str): + Indicates the full name of the ScanConfig field that + triggers this error, for example "scan_config.max_qps". This + field is provided for troubleshooting purposes only and its + actual value can change in the future. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 44 + """ + _pb_options = {'allow_alias': True} + CODE_UNSPECIFIED = 0 + OK = 0 + INTERNAL_ERROR = 1 + APPENGINE_API_BACKEND_ERROR = 2 + APPENGINE_API_NOT_ACCESSIBLE = 3 + APPENGINE_DEFAULT_HOST_MISSING = 4 + CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 + CANNOT_USE_OWNER_ACCOUNT = 7 + COMPUTE_API_BACKEND_ERROR = 8 + COMPUTE_API_NOT_ACCESSIBLE = 9 + CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 + CUSTOM_LOGIN_URL_MALFORMED = 11 + CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 + CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 + CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 + CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 + DUPLICATE_SCAN_NAME = 16 + INVALID_FIELD_VALUE = 18 + FAILED_TO_AUTHENTICATE_TO_TARGET = 19 + FINDING_TYPE_UNSPECIFIED = 20 + FORBIDDEN_TO_SCAN_COMPUTE = 21 + FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 + MALFORMED_FILTER = 22 + MALFORMED_RESOURCE_NAME = 23 + PROJECT_INACTIVE = 24 + REQUIRED_FIELD = 25 + RESOURCE_NAME_INCONSISTENT = 26 + SCAN_ALREADY_RUNNING = 27 + SCAN_NOT_RUNNING = 28 + SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 + SEED_URL_MALFORMED = 30 + SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 + SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 + SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 + SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 + SERVICE_ACCOUNT_NOT_CONFIGURED = 36 + TOO_MANY_SCANS = 37 + UNABLE_TO_RESOLVE_PROJECT_INFO = 38 + UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 + UNSUPPORTED_FILTER = 40 + UNSUPPORTED_FINDING_TYPE = 41 + UNSUPPORTED_URL_SCHEME = 42 + + code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + field_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py new file mode 100644 index 0000000..c7ddcee --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanRun', + }, +) + + +class ScanRun(proto.Message): + r"""A ScanRun is a output-only resource representing an actual + run of the scan. Next id: 12 + + Attributes: + name (str): + The resource name of the ScanRun. The name + follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + The ScanRun IDs are generated by the system. + execution_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ExecutionState): + The execution state of the ScanRun. + result_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ResultState): + The result state of the ScanRun. This field + is only available after the execution state + reaches "FINISHED". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the ScanRun reached + termination state - that the ScanRun is either + finished or stopped by user. + urls_crawled_count (int): + The number of URLs crawled during this + ScanRun. If the scan is in progress, the value + represents the number of URLs crawled up to now. + urls_tested_count (int): + The number of URLs tested during this + ScanRun. If the scan is in progress, the value + represents the number of URLs tested up to now. + The number of URLs tested is usually larger than + the number URLS crawled because typically a + crawled URL is tested with multiple test + payloads. + has_vulnerabilities (bool): + Whether the scan run has found any + vulnerabilities. + progress_percent (int): + The percentage of total completion ranging + from 0 to 100. If the scan is in queue, the + value is 0. If the scan is running, the value + ranges from 0 to 100. If the scan is finished, + the value is 100. + error_trace (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace): + If result_state is an ERROR, this field provides the primary + reason for scan's termination and more details, if such are + available. + warning_traces (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace]): + A list of warnings, if such are encountered + during this scan run. + """ + class ExecutionState(proto.Enum): + r"""Types of ScanRun execution state.""" + EXECUTION_STATE_UNSPECIFIED = 0 + QUEUED = 1 + SCANNING = 2 + FINISHED = 3 + + class ResultState(proto.Enum): + r"""Types of ScanRun result state.""" + RESULT_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + ERROR = 2 + KILLED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + execution_state = proto.Field( + proto.ENUM, + number=2, + enum=ExecutionState, + ) + result_state = proto.Field( + proto.ENUM, + number=3, + enum=ResultState, + ) + start_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + urls_crawled_count = proto.Field( + proto.INT64, + number=6, + ) + urls_tested_count = proto.Field( + proto.INT64, + number=7, + ) + has_vulnerabilities = proto.Field( + proto.BOOL, + number=8, + ) + progress_percent = proto.Field( + proto.INT32, + number=9, + ) + error_trace = proto.Field( + proto.MESSAGE, + number=10, + message=scan_run_error_trace.ScanRunErrorTrace, + ) + warning_traces = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=scan_run_warning_trace.ScanRunWarningTrace, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py new file mode 100644 index 0000000..8f172dc --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1beta.types import scan_config_error as gcw_scan_config_error + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanRunErrorTrace', + }, +) + + +class ScanRunErrorTrace(proto.Message): + r"""Output only. + Defines an error trace message for a ScanRun. + + Attributes: + code (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace.Code): + Indicates the error reason code. + scan_config_error (google.cloud.websecurityscanner_v1beta.types.ScanConfigError): + If the scan encounters SCAN_CONFIG_ISSUE error, this field + has the error message encountered during scan configuration + validation that is performed before each scan run. + most_common_http_error_code (int): + If the scan encounters TOO_MANY_HTTP_ERRORS, this field + indicates the most common HTTP error code, if such is + available. For example, if this code is 404, the scan has + encountered too many NOT_FOUND responses. + """ + class Code(proto.Enum): + r"""Output only. + Defines an error reason code. + Next id: 7 + """ + CODE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + SCAN_CONFIG_ISSUE = 2 + AUTHENTICATION_CONFIG_ISSUE = 3 + TIMED_OUT_WHILE_SCANNING = 4 + TOO_MANY_REDIRECTS = 5 + TOO_MANY_HTTP_ERRORS = 6 + + code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + scan_config_error = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config_error.ScanConfigError, + ) + most_common_http_error_code = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py new file mode 100644 index 0000000..45ef967 --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'ScanRunWarningTrace', + }, +) + + +class ScanRunWarningTrace(proto.Message): + r"""Output only. + Defines a warning trace message for ScanRun. Warning traces + provide customers with useful information that helps make the + scanning process more effective. + + Attributes: + code (google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace.Code): + Indicates the warning code. + """ + class Code(proto.Enum): + r"""Output only. + Defines a warning message code. + Next id: 6 + """ + CODE_UNSPECIFIED = 0 + INSUFFICIENT_CRAWL_RESULTS = 1 + TOO_MANY_CRAWL_RESULTS = 2 + TOO_MANY_FUZZ_TASKS = 3 + BLOCKED_BY_IAP = 4 + + code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py new file mode 100644 index 0000000..04dcf8f --- /dev/null +++ b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py @@ -0,0 +1,463 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats as gcw_finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.websecurityscanner.v1beta', + manifest={ + 'CreateScanConfigRequest', + 'DeleteScanConfigRequest', + 'GetScanConfigRequest', + 'ListScanConfigsRequest', + 'UpdateScanConfigRequest', + 'ListScanConfigsResponse', + 'StartScanRunRequest', + 'GetScanRunRequest', + 'ListScanRunsRequest', + 'ListScanRunsResponse', + 'StopScanRunRequest', + 'ListCrawledUrlsRequest', + 'ListCrawledUrlsResponse', + 'GetFindingRequest', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListFindingTypeStatsRequest', + 'ListFindingTypeStatsResponse', + }, +) + + +class CreateScanConfigRequest(proto.Message): + r"""Request for the ``CreateScanConfig`` method. + Attributes: + parent (str): + Required. The parent resource name where the + scan is created, which should be a project + resource name in the format + 'projects/{projectId}'. + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be created. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + scan_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + + +class DeleteScanConfigRequest(proto.Message): + r"""Request for the ``DeleteScanConfig`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be deleted. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanConfigRequest(proto.Message): + r"""Request for the ``GetScanConfig`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanConfigsRequest(proto.Message): + r"""Request for the ``ListScanConfigs`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a project resource name in the format + 'projects/{projectId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanConfigs to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class UpdateScanConfigRequest(proto.Message): + r"""Request for the ``UpdateScanConfigRequest`` method. + Attributes: + scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): + Required. The ScanConfig to be updated. The + name field must be set to identify the resource + to be updated. The values of fields not covered + by the mask will be ignored. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The update mask applies to the resource. For the + ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + """ + + scan_config = proto.Field( + proto.MESSAGE, + number=2, + message=gcw_scan_config.ScanConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListScanConfigsResponse(proto.Message): + r"""Response for the ``ListScanConfigs`` method. + Attributes: + scan_configs (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig]): + The list of ScanConfigs returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_scan_config.ScanConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class StartScanRunRequest(proto.Message): + r"""Request for the ``StartScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanConfig + to be used. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetScanRunRequest(proto.Message): + r"""Request for the ``GetScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanRun to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScanRunsRequest(proto.Message): + r"""Request for the ``ListScanRuns`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of ScanRuns to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListScanRunsResponse(proto.Message): + r"""Response for the ``ListScanRuns`` method. + Attributes: + scan_runs (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanRun]): + The list of ScanRuns returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + scan_runs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=scan_run.ScanRun, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class StopScanRunRequest(proto.Message): + r"""Request for the ``StopScanRun`` method. + Attributes: + name (str): + Required. The resource name of the ScanRun to + be stopped. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCrawledUrlsRequest(proto.Message): + r"""Request for the ``ListCrawledUrls`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of CrawledUrls to return, + can be limited by server. If not specified or + not positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCrawledUrlsResponse(proto.Message): + r"""Response for the ``ListCrawledUrls`` method. + Attributes: + crawled_urls (Sequence[google.cloud.websecurityscanner_v1beta.types.CrawledUrl]): + The list of CrawledUrls returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + crawled_urls = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=crawled_url.CrawledUrl, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFindingRequest(proto.Message): + r"""Request for the ``GetFinding`` method. + Attributes: + name (str): + Required. The resource name of the Finding to + be returned. The name follows the format of + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request for the ``ListFindings`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + filter (str): + Required. The filter expression. The expression must be in + the format: . Supported field: 'finding_type'. Supported + operator: '='. + page_token (str): + A token identifying a page of results to be returned. This + should be a ``next_page_token`` value returned from a + previous List request. If unspecified, the first page of + results is returned. + page_size (int): + The maximum number of Findings to return, can + be limited by server. If not specified or not + positive, the implementation will select a + reasonable value. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response for the ``ListFindings`` method. + Attributes: + findings (Sequence[google.cloud.websecurityscanner_v1beta.types.Finding]): + The list of Findings returned. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + findings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=finding.Finding, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingTypeStatsRequest(proto.Message): + r"""Request for the ``ListFindingTypeStats`` method. + Attributes: + parent (str): + Required. The parent resource name, which + should be a scan run resource name in the format + 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingTypeStatsResponse(proto.Message): + r"""Response for the ``ListFindingTypeStats`` method. + Attributes: + finding_type_stats (Sequence[google.cloud.websecurityscanner_v1beta.types.FindingTypeStats]): + The list of FindingTypeStats returned. + """ + + finding_type_stats = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcw_finding_type_stats.FindingTypeStats, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/mypy.ini b/owl-bot-staging/v1beta/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta/noxfile.py b/owl-bot-staging/v1beta/noxfile.py new file mode 100644 index 0000000..4ca1ea6 --- /dev/null +++ b/owl-bot-staging/v1beta/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/websecurityscanner_v1beta/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py b/owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py new file mode 100644 index 0000000..5dd19da --- /dev/null +++ b/owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py @@ -0,0 +1,188 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class websecurityscannerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', '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: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=websecurityscannerCallTransformer(), +): + """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 websecurityscanner client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta/setup.py b/owl-bot-staging/v1beta/setup.py new file mode 100644 index 0000000..a33245a --- /dev/null +++ b/owl-bot-staging/v1beta/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-websecurityscanner', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta/tests/__init__.py b/owl-bot-staging/v1beta/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/__init__.py b/owl-bot-staging/v1beta/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py b/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py new file mode 100644 index 0000000..e5c9073 --- /dev/null +++ b/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py @@ -0,0 +1,4961 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerAsyncClient +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerClient +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import transports +from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.websecurityscanner_v1beta.types import crawled_url +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import finding_addon +from google.cloud.websecurityscanner_v1beta.types import finding_type_stats +from google.cloud.websecurityscanner_v1beta.types import scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import scan_config_error +from google.cloud.websecurityscanner_v1beta.types import scan_run +from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace +from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace +from google.cloud.websecurityscanner_v1beta.types import web_security_scanner +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert WebSecurityScannerClient._get_default_mtls_endpoint(None) is None + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + WebSecurityScannerClient, + WebSecurityScannerAsyncClient, +]) +def test_web_security_scanner_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WebSecurityScannerGrpcTransport, "grpc"), + (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + WebSecurityScannerClient, + WebSecurityScannerAsyncClient, +]) +def test_web_security_scanner_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +def test_web_security_scanner_client_get_transport_class(): + transport = WebSecurityScannerClient.get_transport_class() + available_transports = [ + transports.WebSecurityScannerGrpcTransport, + ] + assert transport in available_transports + + transport = WebSecurityScannerClient.get_transport_class("grpc") + assert transport == transports.WebSecurityScannerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +def test_web_security_scanner_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(WebSecurityScannerClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(WebSecurityScannerClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) +@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_web_security_scanner_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), + (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_web_security_scanner_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_web_security_scanner_client_client_options_from_dict(): + with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebSecurityScannerClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_create_scan_config(transport: str = 'grpc', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + response = client.create_scan_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] == web_security_scanner.CreateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_create_scan_config_from_dict(): + test_create_scan_config(request_type=dict) + + +def test_create_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + client.create_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest() + + +@pytest.mark.asyncio +async def test_create_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + )) + response = await client.create_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.CreateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.asyncio +async def test_create_scan_config_async_from_dict(): + await test_create_scan_config_async(request_type=dict) + + +def test_create_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.create_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.CreateScanConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.create_scan_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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') + + +def test_create_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scan_config( + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') + + +@pytest.mark.asyncio +async def test_create_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent='parent_value', + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + ) + + +def test_delete_scan_config(transport: str = 'grpc', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scan_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] == web_security_scanner.DeleteScanConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_from_dict(): + test_delete_scan_config(request_type=dict) + + +def test_delete_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + client.delete_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.DeleteScanConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_scan_config_async_from_dict(): + await test_delete_scan_config_async(request_type=dict) + + +def test_delete_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = None + client.delete_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.DeleteScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scan_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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name='name_value', + ) + + +def test_get_scan_config(transport: str = 'grpc', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + ) + response = client.get_scan_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] == web_security_scanner.GetScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_get_scan_config_from_dict(): + test_get_scan_config(request_type=dict) + + +def test_get_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + client.get_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest() + + +@pytest.mark.asyncio +async def test_get_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + )) + response = await client.get_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.asyncio +async def test_get_scan_config_async_from_dict(): + await test_get_scan_config_async(request_type=dict) + + +def test_get_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = scan_config.ScanConfig() + client.get_scan_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_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + await client.get_scan_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_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_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_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_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_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scan_config( + web_security_scanner.GetScanConfigRequest(), + name='name_value', + ) + + +def test_list_scan_configs(transport: str = 'grpc', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_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] == web_security_scanner.ListScanConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_configs_from_dict(): + test_list_scan_configs(request_type=dict) + + +def test_list_scan_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + client.list_scan_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_configs_async_from_dict(): + await test_list_scan_configs_async(request_type=dict) + + +def test_list_scan_configs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanConfigsResponse() + client.list_scan_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_scan_configs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + await client.list_scan_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_scan_configs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_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_scan_configs_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_scan_configs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_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_scan_configs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent='parent_value', + ) + + +def test_list_scan_configs_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_configs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) + for i in results) + +def test_list_scan_configs_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_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_scan_configs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_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, scan_config.ScanConfig) + for i in responses) + +@pytest.mark.asyncio +async def test_list_scan_configs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token='def', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_scan_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_update_scan_config(transport: str = 'grpc', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + response = client.update_scan_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] == web_security_scanner.UpdateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_update_scan_config_from_dict(): + test_update_scan_config(request_type=dict) + + +def test_update_scan_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + client.update_scan_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest() + + +@pytest.mark.asyncio +async def test_update_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( + name='name_value', + display_name='display_name_value', + max_qps=761, + starting_urls=['starting_urls_value'], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=['blacklist_patterns_value'], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + )) + response = await client.update_scan_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.UpdateScanConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.max_qps == 761 + assert response.starting_urls == ['starting_urls_value'] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ['blacklist_patterns_value'] + assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] + assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +@pytest.mark.asyncio +async def test_update_scan_config_async_from_dict(): + await test_update_scan_config_async(request_type=dict) + + +def test_update_scan_config_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'scan_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = gcw_scan_config.ScanConfig() + client.update_scan_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', + 'scan_config.name=scan_config.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_scan_config_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.UpdateScanConfigRequest() + + request.scan_config.name = 'scan_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + await client.update_scan_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', + 'scan_config.name=scan_config.name/value', + ) in kw['metadata'] + + +def test_update_scan_config_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_scan_config_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_scan_config_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scan_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcw_scan_config.ScanConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scan_config( + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_scan_config_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_start_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_from_dict(): + test_start_scan_run(request_type=dict) + + +def test_start_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + client.start_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + +@pytest.mark.asyncio +async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StartScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_start_scan_run_async_from_dict(): + await test_start_scan_run_async(request_type=dict) + + +def test_start_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_start_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StartScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.start_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_start_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_scan_run( + 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_start_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_start_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_scan_run( + 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_start_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name='name_value', + ) + + +def test_get_scan_run(transport: str = 'grpc', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_from_dict(): + test_get_scan_run(request_type=dict) + + +def test_get_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + client.get_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + +@pytest.mark.asyncio +async def test_get_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_get_scan_run_async_from_dict(): + await test_get_scan_run_async(request_type=dict) + + +def test_get_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.get_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scan_run( + 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_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scan_run( + 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_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scan_run( + web_security_scanner.GetScanRunRequest(), + name='name_value', + ) + + +def test_list_scan_runs(transport: str = 'grpc', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_scan_runs_from_dict(): + test_list_scan_runs(request_type=dict) + + +def test_list_scan_runs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + client.list_scan_runs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + +@pytest.mark.asyncio +async def test_list_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListScanRunsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_scan_runs_async_from_dict(): + await test_list_scan_runs_async(request_type=dict) + + +def test_list_scan_runs_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = web_security_scanner.ListScanRunsResponse() + client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_scan_runs_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListScanRunsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + await client.list_scan_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_scan_runs_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scan_runs( + 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_scan_runs_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_scan_runs_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListScanRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scan_runs( + 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_scan_runs_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent='parent_value', + ) + + +def test_list_scan_runs_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_scan_runs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) + for i in results) + +def test_list_scan_runs_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scan_runs(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_scan_runs_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scan_runs(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, scan_run.ScanRun) + for i in responses) + +@pytest.mark.asyncio +async def test_list_scan_runs_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scan_runs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token='abc', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token='def', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_scan_runs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_stop_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + response = client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_from_dict(): + test_stop_scan_run(request_type=dict) + + +def test_stop_scan_run_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + client.stop_scan_run() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + +@pytest.mark.asyncio +async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( + name='name_value', + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + )) + response = await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.StopScanRunRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == 'name_value' + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.asyncio +async def test_stop_scan_run_async_from_dict(): + await test_stop_scan_run_async(request_type=dict) + + +def test_stop_scan_run_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = scan_run.ScanRun() + client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_stop_scan_run_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.StopScanRunRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + await client.stop_scan_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_stop_scan_run_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_scan_run( + 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_stop_scan_run_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_stop_scan_run_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_scan_run), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = scan_run.ScanRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_scan_run( + 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_stop_scan_run_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name='name_value', + ) + + +def test_list_crawled_urls(transport: str = 'grpc', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_crawled_urls_from_dict(): + test_list_crawled_urls(request_type=dict) + + +def test_list_crawled_urls_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + client.list_crawled_urls() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListCrawledUrlsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_from_dict(): + await test_list_crawled_urls_async(request_type=dict) + + +def test_list_crawled_urls_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_crawled_urls_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListCrawledUrlsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + await client.list_crawled_urls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_crawled_urls_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crawled_urls( + 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_crawled_urls_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_crawled_urls_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListCrawledUrlsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crawled_urls( + 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_crawled_urls_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent='parent_value', + ) + + +def test_list_crawled_urls_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crawled_urls(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) + for i in results) + +def test_list_crawled_urls_pages(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) + for i in responses) + +@pytest.mark.asyncio +async def test_list_crawled_urls_async_pages(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crawled_urls), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token='abc', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token='def', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token='ghi', + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_crawled_urls(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_finding(transport: str = 'grpc', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + finding_type='finding_type_value', + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + ) + response = client.get_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] == web_security_scanner.GetFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +def test_get_finding_from_dict(): + test_get_finding(request_type=dict) + + +def test_get_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + client.get_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest() + + +@pytest.mark.asyncio +async def test_get_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + finding_type='finding_type_value', + http_method='http_method_value', + fuzzed_url='fuzzed_url_value', + body='body_value', + description='description_value', + reproduction_url='reproduction_url_value', + frame_url='frame_url_value', + final_url='final_url_value', + tracking_id='tracking_id_value', + )) + response = await client.get_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.GetFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.finding_type == 'finding_type_value' + assert response.http_method == 'http_method_value' + assert response.fuzzed_url == 'fuzzed_url_value' + assert response.body == 'body_value' + assert response.description == 'description_value' + assert response.reproduction_url == 'reproduction_url_value' + assert response.frame_url == 'frame_url_value' + assert response.final_url == 'final_url_value' + assert response.tracking_id == 'tracking_id_value' + + +@pytest.mark.asyncio +async def test_get_finding_async_from_dict(): + await test_get_finding_async(request_type=dict) + + +def test_get_finding_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = finding.Finding() + client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_finding_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.GetFindingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.get_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', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_finding_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__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.get_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].name == 'name_value' + + +def test_get_finding_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_finding_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_finding), + '__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.get_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].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_finding_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_finding( + web_security_scanner.GetFindingRequest(), + name='name_value', + ) + + +def test_list_findings(transport: str = 'grpc', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + ) + 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] == web_security_scanner.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' + + +def test_list_findings_from_dict(): + test_list_findings(request_type=dict) + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( + next_page_token='next_page_token_value', + )) + 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] == web_security_scanner.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.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 = web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.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', + filter='filter_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].filter == 'filter_value' + + +def test_list_findings_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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', + filter='filter_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].filter == 'filter_value' + + +@pytest.mark.asyncio +async def test_list_findings_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + web_security_scanner.ListFindingsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_findings_pager(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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 = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + web_security_scanner.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_finding_type_stats(transport: str = 'grpc', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse( + ) + response = client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_from_dict(): + test_list_finding_type_stats(request_type=dict) + + +def test_list_finding_type_stats_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + client.list_finding_type_stats() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( + )) + response = await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_async_from_dict(): + await test_list_finding_type_stats_async(request_type=dict) + + +def test_list_finding_type_stats_field_headers(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_finding_type_stats_field_headers_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = web_security_scanner.ListFindingTypeStatsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + await client.list_finding_type_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_finding_type_stats_flattened(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_finding_type_stats( + 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_finding_type_stats_flattened_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_finding_type_stats_flattened_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_finding_type_stats), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_finding_type_stats( + 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_finding_type_stats_flattened_error_async(): + client = WebSecurityScannerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_scan_config', + 'delete_scan_config', + 'get_scan_config', + 'list_scan_configs', + 'update_scan_config', + 'start_scan_run', + 'get_scan_run', + 'list_scan_runs', + 'stop_scan_run', + 'list_crawled_urls', + 'get_finding', + 'list_findings', + 'list_finding_type_stats', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + 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_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebSecurityScannerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebSecurityScannerClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_web_security_scanner_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_web_security_scanner_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebSecurityScannerGrpcTransport, grpc_helpers), + (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_web_security_scanner_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "websecurityscanner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="websecurityscanner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_web_security_scanner_host_no_port(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), + ) + assert client.transport._host == 'websecurityscanner.googleapis.com:443' + + +def test_web_security_scanner_host_with_port(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), + ) + assert client.transport._host == 'websecurityscanner.googleapis.com:8000' + +def test_web_security_scanner_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_web_security_scanner_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) +def test_web_security_scanner_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_finding_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + finding = "octopus" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) + actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "project": "oyster", + "scan_config": "nudibranch", + "scan_run": "cuttlefish", + "finding": "mussel", + } + path = WebSecurityScannerClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_finding_path(path) + assert expected == actual + +def test_scan_config_path(): + project = "winkle" + scan_config = "nautilus" + expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) + actual = WebSecurityScannerClient.scan_config_path(project, scan_config) + assert expected == actual + + +def test_parse_scan_config_path(): + expected = { + "project": "scallop", + "scan_config": "abalone", + } + path = WebSecurityScannerClient.scan_config_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_config_path(path) + assert expected == actual + +def test_scan_run_path(): + project = "squid" + scan_config = "clam" + scan_run = "whelk" + expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) + actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) + assert expected == actual + + +def test_parse_scan_run_path(): + expected = { + "project": "octopus", + "scan_config": "oyster", + "scan_run": "nudibranch", + } + path = WebSecurityScannerClient.scan_run_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_scan_run_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebSecurityScannerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = WebSecurityScannerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebSecurityScannerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = WebSecurityScannerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebSecurityScannerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = WebSecurityScannerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = WebSecurityScannerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = WebSecurityScannerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = WebSecurityScannerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = WebSecurityScannerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebSecurityScannerClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: + transport_class = WebSecurityScannerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From c70610d6e0a385ee2e55bcbcbff553e199016102 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 23 Sep 2021 18:57:20 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/web_security_scanner/client.py | 54 +- .../web_security_scanner/transports/base.py | 2 +- .../web_security_scanner/transports/grpc.py | 6 +- .../transports/grpc_asyncio.py | 6 +- .../services/web_security_scanner/client.py | 54 +- .../web_security_scanner/transports/base.py | 2 +- .../web_security_scanner/transports/grpc.py | 6 +- .../transports/grpc_asyncio.py | 6 +- .../services/web_security_scanner/client.py | 54 +- .../web_security_scanner/transports/base.py | 2 +- .../web_security_scanner/transports/grpc.py | 6 +- .../transports/grpc_asyncio.py | 6 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 -- owl-bot-staging/v1/docs/index.rst | 7 - .../docs/websecurityscanner_v1/services.rst | 6 - .../v1/docs/websecurityscanner_v1/types.rst | 7 - .../web_security_scanner.rst | 10 - .../cloud/websecurityscanner/__init__.py | 87 - .../google/cloud/websecurityscanner/py.typed | 2 - .../cloud/websecurityscanner_v1/__init__.py | 88 - .../websecurityscanner_v1/gapic_metadata.json | 153 - .../cloud/websecurityscanner_v1/py.typed | 2 - .../services/__init__.py | 15 - .../services/web_security_scanner/__init__.py | 22 - .../web_security_scanner/async_client.py | 992 ---- .../services/web_security_scanner/client.py | 1133 ---- .../services/web_security_scanner/pagers.py | 510 -- .../transports/__init__.py | 33 - .../web_security_scanner/transports/base.py | 403 -- .../web_security_scanner/transports/grpc.py | 574 -- .../transports/grpc_asyncio.py | 578 -- .../websecurityscanner_v1/types/__init__.py | 102 - .../types/crawled_url.py | 58 - .../websecurityscanner_v1/types/finding.py | 185 - .../types/finding_addon.py | 206 - .../types/finding_type_stats.py | 50 - .../types/scan_config.py | 299 - .../types/scan_config_error.py | 103 - .../websecurityscanner_v1/types/scan_run.py | 151 - .../types/scan_run_error_trace.py | 76 - .../types/scan_run_warning_trace.py | 55 - .../types/web_security_scanner.py | 462 -- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../fixup_websecurityscanner_v1_keywords.py | 188 - owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/websecurityscanner_v1/__init__.py | 16 - .../test_web_security_scanner.py | 3877 ------------- owl-bot-staging/v1alpha/.coveragerc | 17 - owl-bot-staging/v1alpha/MANIFEST.in | 2 - owl-bot-staging/v1alpha/README.rst | 49 - owl-bot-staging/v1alpha/docs/conf.py | 376 -- owl-bot-staging/v1alpha/docs/index.rst | 7 - .../websecurityscanner_v1alpha/services.rst | 6 - .../docs/websecurityscanner_v1alpha/types.rst | 7 - .../web_security_scanner.rst | 10 - .../cloud/websecurityscanner/__init__.py | 79 - .../google/cloud/websecurityscanner/py.typed | 2 - .../websecurityscanner_v1alpha/__init__.py | 80 - .../gapic_metadata.json | 153 - .../cloud/websecurityscanner_v1alpha/py.typed | 2 - .../services/__init__.py | 15 - .../services/web_security_scanner/__init__.py | 22 - .../web_security_scanner/async_client.py | 1314 ----- .../services/web_security_scanner/client.py | 1460 ----- .../services/web_security_scanner/pagers.py | 510 -- .../transports/__init__.py | 33 - .../web_security_scanner/transports/base.py | 404 -- .../web_security_scanner/transports/grpc.py | 575 -- .../transports/grpc_asyncio.py | 579 -- .../types/__init__.py | 88 - .../types/crawled_url.py | 58 - .../types/finding.py | 168 - .../types/finding_addon.py | 151 - .../types/finding_type_stats.py | 52 - .../types/scan_config.py | 229 - .../types/scan_run.py | 129 - .../types/web_security_scanner.py | 463 -- owl-bot-staging/v1alpha/mypy.ini | 3 - owl-bot-staging/v1alpha/noxfile.py | 132 - ...xup_websecurityscanner_v1alpha_keywords.py | 188 - owl-bot-staging/v1alpha/setup.py | 54 - owl-bot-staging/v1alpha/tests/__init__.py | 16 - .../v1alpha/tests/unit/__init__.py | 16 - .../v1alpha/tests/unit/gapic/__init__.py | 16 - .../websecurityscanner_v1alpha/__init__.py | 16 - .../test_web_security_scanner.py | 4934 ---------------- owl-bot-staging/v1beta/.coveragerc | 17 - owl-bot-staging/v1beta/MANIFEST.in | 2 - owl-bot-staging/v1beta/README.rst | 49 - owl-bot-staging/v1beta/docs/conf.py | 376 -- owl-bot-staging/v1beta/docs/index.rst | 7 - .../websecurityscanner_v1beta/services.rst | 6 - .../docs/websecurityscanner_v1beta/types.rst | 7 - .../web_security_scanner.rst | 10 - .../cloud/websecurityscanner/__init__.py | 87 - .../google/cloud/websecurityscanner/py.typed | 2 - .../websecurityscanner_v1beta/__init__.py | 88 - .../gapic_metadata.json | 153 - .../cloud/websecurityscanner_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/web_security_scanner/__init__.py | 22 - .../web_security_scanner/async_client.py | 1316 ----- .../services/web_security_scanner/client.py | 1462 ----- .../services/web_security_scanner/pagers.py | 510 -- .../transports/__init__.py | 33 - .../web_security_scanner/transports/base.py | 404 -- .../web_security_scanner/transports/grpc.py | 575 -- .../transports/grpc_asyncio.py | 579 -- .../types/__init__.py | 102 - .../types/crawled_url.py | 58 - .../types/finding.py | 165 - .../types/finding_addon.py | 173 - .../types/finding_type_stats.py | 49 - .../types/scan_config.py | 262 - .../types/scan_config_error.py | 103 - .../types/scan_run.py | 148 - .../types/scan_run_error_trace.py | 75 - .../types/scan_run_warning_trace.py | 55 - .../types/web_security_scanner.py | 463 -- owl-bot-staging/v1beta/mypy.ini | 3 - owl-bot-staging/v1beta/noxfile.py | 132 - ...ixup_websecurityscanner_v1beta_keywords.py | 188 - owl-bot-staging/v1beta/setup.py | 54 - owl-bot-staging/v1beta/tests/__init__.py | 16 - owl-bot-staging/v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../websecurityscanner_v1beta/__init__.py | 16 - .../test_web_security_scanner.py | 4961 ----------------- .../fixup_websecurityscanner_v1_keywords.py | 28 +- ...xup_websecurityscanner_v1alpha_keywords.py | 28 +- ...ixup_websecurityscanner_v1beta_keywords.py | 28 +- 138 files changed, 144 insertions(+), 36467 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py delete mode 100644 owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py delete mode 100644 owl-bot-staging/v1alpha/.coveragerc delete mode 100644 owl-bot-staging/v1alpha/MANIFEST.in delete mode 100644 owl-bot-staging/v1alpha/README.rst delete mode 100644 owl-bot-staging/v1alpha/docs/conf.py delete mode 100644 owl-bot-staging/v1alpha/docs/index.rst delete mode 100644 owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst delete mode 100644 owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst delete mode 100644 owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py delete mode 100644 owl-bot-staging/v1alpha/mypy.ini delete mode 100644 owl-bot-staging/v1alpha/noxfile.py delete mode 100644 owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py delete mode 100644 owl-bot-staging/v1alpha/setup.py delete mode 100644 owl-bot-staging/v1alpha/tests/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py delete mode 100644 owl-bot-staging/v1beta/.coveragerc delete mode 100644 owl-bot-staging/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta/README.rst delete mode 100644 owl-bot-staging/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst delete mode 100644 owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst delete mode 100644 owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py delete mode 100644 owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py delete mode 100644 owl-bot-staging/v1beta/mypy.ini delete mode 100644 owl-bot-staging/v1beta/noxfile.py delete mode 100644 owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py delete mode 100644 owl-bot-staging/v1beta/setup.py delete mode 100644 owl-bot-staging/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py delete mode 100644 owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py index 7881267..4bb4719 100644 --- a/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -372,7 +372,7 @@ def __init__( def create_scan_config( self, - request: web_security_scanner.CreateScanConfigRequest = None, + request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -381,7 +381,7 @@ def create_scan_config( r"""Creates a new ScanConfig. Args: - request (google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]): The request object. Request for the `CreateScanConfig` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -422,7 +422,7 @@ def create_scan_config( def delete_scan_config( self, - request: web_security_scanner.DeleteScanConfigRequest = None, + request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -432,7 +432,7 @@ def delete_scan_config( resources. Args: - request (google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]): The request object. Request for the `DeleteScanConfig` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -466,7 +466,7 @@ def delete_scan_config( def get_scan_config( self, - request: web_security_scanner.GetScanConfigRequest = None, + request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -475,7 +475,7 @@ def get_scan_config( r"""Gets a ScanConfig. Args: - request (google.cloud.websecurityscanner_v1.types.GetScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]): The request object. Request for the `GetScanConfig` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -516,7 +516,7 @@ def get_scan_config( def list_scan_configs( self, - request: web_security_scanner.ListScanConfigsRequest = None, + request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -525,7 +525,7 @@ def list_scan_configs( r"""Lists ScanConfigs under a given project. Args: - request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): + request (Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]): The request object. Request for the `ListScanConfigs` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -574,7 +574,7 @@ def list_scan_configs( def update_scan_config( self, - request: web_security_scanner.UpdateScanConfigRequest = None, + request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -584,7 +584,7 @@ def update_scan_config( update of a ScanConfig. Args: - request (google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]): The request object. Request for the `UpdateScanConfigRequest` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -627,7 +627,7 @@ def update_scan_config( def start_scan_run( self, - request: web_security_scanner.StartScanRunRequest = None, + request: Union[web_security_scanner.StartScanRunRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -636,7 +636,7 @@ def start_scan_run( r"""Start a ScanRun according to the given ScanConfig. Args: - request (google.cloud.websecurityscanner_v1.types.StartScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]): The request object. Request for the `StartScanRun` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -678,7 +678,7 @@ def start_scan_run( def get_scan_run( self, - request: web_security_scanner.GetScanRunRequest = None, + request: Union[web_security_scanner.GetScanRunRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -687,7 +687,7 @@ def get_scan_run( r"""Gets a ScanRun. Args: - request (google.cloud.websecurityscanner_v1.types.GetScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]): The request object. Request for the `GetScanRun` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -728,7 +728,7 @@ def get_scan_run( def list_scan_runs( self, - request: web_security_scanner.ListScanRunsRequest = None, + request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -738,7 +738,7 @@ def list_scan_runs( descending order of ScanRun stop time. Args: - request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): + request (Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]): The request object. Request for the `ListScanRuns` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -787,7 +787,7 @@ def list_scan_runs( def stop_scan_run( self, - request: web_security_scanner.StopScanRunRequest = None, + request: Union[web_security_scanner.StopScanRunRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -796,7 +796,7 @@ def stop_scan_run( r"""Stops a ScanRun. The stopped ScanRun is returned. Args: - request (google.cloud.websecurityscanner_v1.types.StopScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]): The request object. Request for the `StopScanRun` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -838,7 +838,7 @@ def stop_scan_run( def list_crawled_urls( self, - request: web_security_scanner.ListCrawledUrlsRequest = None, + request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -847,7 +847,7 @@ def list_crawled_urls( r"""List CrawledUrls under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): + request (Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]): The request object. Request for the `ListCrawledUrls` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -896,7 +896,7 @@ def list_crawled_urls( def get_finding( self, - request: web_security_scanner.GetFindingRequest = None, + request: Union[web_security_scanner.GetFindingRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -905,7 +905,7 @@ def get_finding( r"""Gets a Finding. Args: - request (google.cloud.websecurityscanner_v1.types.GetFindingRequest): + request (Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]): The request object. Request for the `GetFinding` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -946,7 +946,7 @@ def get_finding( def list_findings( self, - request: web_security_scanner.ListFindingsRequest = None, + request: Union[web_security_scanner.ListFindingsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -955,7 +955,7 @@ def list_findings( r"""List Findings under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): + request (Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]): The request object. Request for the `ListFindings` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -1004,7 +1004,7 @@ def list_findings( def list_finding_type_stats( self, - request: web_security_scanner.ListFindingTypeStatsRequest = None, + request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -1013,7 +1013,7 @@ def list_finding_type_stats( r"""List all FindingTypeStats under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest): + request (Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]): The request object. Request for the `ListFindingTypeStats` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py index 78a037b..13530f8 100644 --- a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py @@ -121,7 +121,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py index 04cf05b..b8767c3 100644 --- a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py @@ -87,16 +87,16 @@ def __init__( 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`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py index 79827a3..6de2096 100644 --- a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py @@ -134,16 +134,16 @@ def __init__( 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`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py index 8e615b0..d8c650f 100644 --- a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -403,7 +403,7 @@ def __init__( def create_scan_config( self, - request: web_security_scanner.CreateScanConfigRequest = None, + request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, *, parent: str = None, scan_config: gcw_scan_config.ScanConfig = None, @@ -414,7 +414,7 @@ def create_scan_config( r"""Creates a new ScanConfig. Args: - request (google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]): The request object. Request for the `CreateScanConfig` method. parent (str): @@ -487,7 +487,7 @@ def create_scan_config( def delete_scan_config( self, - request: web_security_scanner.DeleteScanConfigRequest = None, + request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -498,7 +498,7 @@ def delete_scan_config( resources. Args: - request (google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]): The request object. Request for the `DeleteScanConfig` method. name (str): @@ -554,7 +554,7 @@ def delete_scan_config( def get_scan_config( self, - request: web_security_scanner.GetScanConfigRequest = None, + request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -564,7 +564,7 @@ def get_scan_config( r"""Gets a ScanConfig. Args: - request (google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]): The request object. Request for the `GetScanConfig` method. name (str): @@ -628,7 +628,7 @@ def get_scan_config( def list_scan_configs( self, - request: web_security_scanner.ListScanConfigsRequest = None, + request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -638,7 +638,7 @@ def list_scan_configs( r"""Lists ScanConfigs under a given project. Args: - request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]): The request object. Request for the `ListScanConfigs` method. parent (str): @@ -708,7 +708,7 @@ def list_scan_configs( def update_scan_config( self, - request: web_security_scanner.UpdateScanConfigRequest = None, + request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, *, scan_config: gcw_scan_config.ScanConfig = None, update_mask: field_mask_pb2.FieldMask = None, @@ -720,7 +720,7 @@ def update_scan_config( update of a ScanConfig. Args: - request (google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]): The request object. Request for the `UpdateScanConfigRequest` method. scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): @@ -797,7 +797,7 @@ def update_scan_config( def start_scan_run( self, - request: web_security_scanner.StartScanRunRequest = None, + request: Union[web_security_scanner.StartScanRunRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -807,7 +807,7 @@ def start_scan_run( r"""Start a ScanRun according to the given ScanConfig. Args: - request (google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]): The request object. Request for the `StartScanRun` method. name (str): @@ -870,7 +870,7 @@ def start_scan_run( def get_scan_run( self, - request: web_security_scanner.GetScanRunRequest = None, + request: Union[web_security_scanner.GetScanRunRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -880,7 +880,7 @@ def get_scan_run( r"""Gets a ScanRun. Args: - request (google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]): The request object. Request for the `GetScanRun` method. name (str): Required. The resource name of the @@ -942,7 +942,7 @@ def get_scan_run( def list_scan_runs( self, - request: web_security_scanner.ListScanRunsRequest = None, + request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -953,7 +953,7 @@ def list_scan_runs( descending order of ScanRun stop time. Args: - request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]): The request object. Request for the `ListScanRuns` method. parent (str): @@ -1024,7 +1024,7 @@ def list_scan_runs( def stop_scan_run( self, - request: web_security_scanner.StopScanRunRequest = None, + request: Union[web_security_scanner.StopScanRunRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1034,7 +1034,7 @@ def stop_scan_run( r"""Stops a ScanRun. The stopped ScanRun is returned. Args: - request (google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]): The request object. Request for the `StopScanRun` method. name (str): @@ -1097,7 +1097,7 @@ def stop_scan_run( def list_crawled_urls( self, - request: web_security_scanner.ListCrawledUrlsRequest = None, + request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1107,7 +1107,7 @@ def list_crawled_urls( r"""List CrawledUrls under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]): The request object. Request for the `ListCrawledUrls` method. parent (str): @@ -1178,7 +1178,7 @@ def list_crawled_urls( def get_finding( self, - request: web_security_scanner.GetFindingRequest = None, + request: Union[web_security_scanner.GetFindingRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1188,7 +1188,7 @@ def get_finding( r"""Gets a Finding. Args: - request (google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]): The request object. Request for the `GetFinding` method. name (str): Required. The resource name of the @@ -1251,7 +1251,7 @@ def get_finding( def list_findings( self, - request: web_security_scanner.ListFindingsRequest = None, + request: Union[web_security_scanner.ListFindingsRequest, dict] = None, *, parent: str = None, filter: str = None, @@ -1262,7 +1262,7 @@ def list_findings( r"""List Findings under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]): The request object. Request for the `ListFindings` method. parent (str): @@ -1343,7 +1343,7 @@ def list_findings( def list_finding_type_stats( self, - request: web_security_scanner.ListFindingTypeStatsRequest = None, + request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1353,7 +1353,7 @@ def list_finding_type_stats( r"""List all FindingTypeStats under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest): + request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]): The request object. Request for the `ListFindingTypeStats` method. parent (str): diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py index 5057c45..0d32f74 100644 --- a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py @@ -122,7 +122,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py index 97d0d28..4b25911 100644 --- a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py @@ -88,16 +88,16 @@ def __init__( 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`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py index 7296a6d..400e2b1 100644 --- a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py @@ -135,16 +135,16 @@ def __init__( 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`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py index 29a0910..736ae09 100644 --- a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -405,7 +405,7 @@ def __init__( def create_scan_config( self, - request: web_security_scanner.CreateScanConfigRequest = None, + request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, *, parent: str = None, scan_config: gcw_scan_config.ScanConfig = None, @@ -416,7 +416,7 @@ def create_scan_config( r"""Creates a new ScanConfig. Args: - request (google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]): The request object. Request for the `CreateScanConfig` method. parent (str): @@ -488,7 +488,7 @@ def create_scan_config( def delete_scan_config( self, - request: web_security_scanner.DeleteScanConfigRequest = None, + request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -499,7 +499,7 @@ def delete_scan_config( resources. Args: - request (google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]): The request object. Request for the `DeleteScanConfig` method. name (str): @@ -555,7 +555,7 @@ def delete_scan_config( def get_scan_config( self, - request: web_security_scanner.GetScanConfigRequest = None, + request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -565,7 +565,7 @@ def get_scan_config( r"""Gets a ScanConfig. Args: - request (google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]): The request object. Request for the `GetScanConfig` method. name (str): @@ -628,7 +628,7 @@ def get_scan_config( def list_scan_configs( self, - request: web_security_scanner.ListScanConfigsRequest = None, + request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -638,7 +638,7 @@ def list_scan_configs( r"""Lists ScanConfigs under a given project. Args: - request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]): The request object. Request for the `ListScanConfigs` method. parent (str): @@ -708,7 +708,7 @@ def list_scan_configs( def update_scan_config( self, - request: web_security_scanner.UpdateScanConfigRequest = None, + request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, *, scan_config: gcw_scan_config.ScanConfig = None, update_mask: field_mask_pb2.FieldMask = None, @@ -720,7 +720,7 @@ def update_scan_config( update of a ScanConfig. Args: - request (google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]): The request object. Request for the `UpdateScanConfigRequest` method. scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): @@ -796,7 +796,7 @@ def update_scan_config( def start_scan_run( self, - request: web_security_scanner.StartScanRunRequest = None, + request: Union[web_security_scanner.StartScanRunRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -806,7 +806,7 @@ def start_scan_run( r"""Start a ScanRun according to the given ScanConfig. Args: - request (google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]): The request object. Request for the `StartScanRun` method. name (str): @@ -870,7 +870,7 @@ def start_scan_run( def get_scan_run( self, - request: web_security_scanner.GetScanRunRequest = None, + request: Union[web_security_scanner.GetScanRunRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -880,7 +880,7 @@ def get_scan_run( r"""Gets a ScanRun. Args: - request (google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]): The request object. Request for the `GetScanRun` method. name (str): Required. The resource name of the @@ -943,7 +943,7 @@ def get_scan_run( def list_scan_runs( self, - request: web_security_scanner.ListScanRunsRequest = None, + request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -954,7 +954,7 @@ def list_scan_runs( descending order of ScanRun stop time. Args: - request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]): The request object. Request for the `ListScanRuns` method. parent (str): @@ -1025,7 +1025,7 @@ def list_scan_runs( def stop_scan_run( self, - request: web_security_scanner.StopScanRunRequest = None, + request: Union[web_security_scanner.StopScanRunRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1035,7 +1035,7 @@ def stop_scan_run( r"""Stops a ScanRun. The stopped ScanRun is returned. Args: - request (google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]): The request object. Request for the `StopScanRun` method. name (str): @@ -1099,7 +1099,7 @@ def stop_scan_run( def list_crawled_urls( self, - request: web_security_scanner.ListCrawledUrlsRequest = None, + request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1109,7 +1109,7 @@ def list_crawled_urls( r"""List CrawledUrls under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]): The request object. Request for the `ListCrawledUrls` method. parent (str): @@ -1180,7 +1180,7 @@ def list_crawled_urls( def get_finding( self, - request: web_security_scanner.GetFindingRequest = None, + request: Union[web_security_scanner.GetFindingRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1190,7 +1190,7 @@ def get_finding( r"""Gets a Finding. Args: - request (google.cloud.websecurityscanner_v1beta.types.GetFindingRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]): The request object. Request for the `GetFinding` method. name (str): Required. The resource name of the @@ -1253,7 +1253,7 @@ def get_finding( def list_findings( self, - request: web_security_scanner.ListFindingsRequest = None, + request: Union[web_security_scanner.ListFindingsRequest, dict] = None, *, parent: str = None, filter: str = None, @@ -1264,7 +1264,7 @@ def list_findings( r"""List Findings under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]): The request object. Request for the `ListFindings` method. parent (str): @@ -1345,7 +1345,7 @@ def list_findings( def list_finding_type_stats( self, - request: web_security_scanner.ListFindingTypeStatsRequest = None, + request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1355,7 +1355,7 @@ def list_finding_type_stats( r"""List all FindingTypeStats under a given ScanRun. Args: - request (google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest): + request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]): The request object. Request for the `ListFindingTypeStats` method. parent (str): diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py index 2ec097f..2dbb73a 100644 --- a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py @@ -122,7 +122,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py index 5a8f541..1bc7090 100644 --- a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py @@ -88,16 +88,16 @@ def __init__( 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`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py index 15bcfab..b7649be 100644 --- a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py @@ -135,16 +135,16 @@ def __init__( 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`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 6b433c1..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/websecurityscanner/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 9d26e3b..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/websecurityscanner *.py -recursive-include google/cloud/websecurityscanner_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 4de4c10..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Websecurityscanner API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Websecurityscanner API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index c393cbd..0000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-websecurityscanner documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-websecurityscanner" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-websecurityscanner-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-websecurityscanner.tex", - u"google-cloud-websecurityscanner Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-websecurityscanner", - u"Google Cloud Websecurityscanner Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-websecurityscanner", - u"google-cloud-websecurityscanner Documentation", - author, - "google-cloud-websecurityscanner", - "GAPIC library for Google Cloud Websecurityscanner API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index f8b680d..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - websecurityscanner_v1/services - websecurityscanner_v1/types diff --git a/owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst b/owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst deleted file mode 100644 index 6fb98e6..0000000 --- a/owl-bot-staging/v1/docs/websecurityscanner_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Websecurityscanner v1 API -=================================================== -.. toctree:: - :maxdepth: 2 - - web_security_scanner diff --git a/owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst b/owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst deleted file mode 100644 index aadd787..0000000 --- a/owl-bot-staging/v1/docs/websecurityscanner_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Websecurityscanner v1 API -================================================ - -.. automodule:: google.cloud.websecurityscanner_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst b/owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst deleted file mode 100644 index 4925421..0000000 --- a/owl-bot-staging/v1/docs/websecurityscanner_v1/web_security_scanner.rst +++ /dev/null @@ -1,10 +0,0 @@ -WebSecurityScanner ------------------------------------- - -.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner - :members: - :inherited-members: - -.. automodule:: google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py deleted file mode 100644 index e83d0b5..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.websecurityscanner_v1.services.web_security_scanner.client import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient - -from google.cloud.websecurityscanner_v1.types.crawled_url import CrawledUrl -from google.cloud.websecurityscanner_v1.types.finding import Finding -from google.cloud.websecurityscanner_v1.types.finding_addon import Form -from google.cloud.websecurityscanner_v1.types.finding_addon import OutdatedLibrary -from google.cloud.websecurityscanner_v1.types.finding_addon import ViolatingResource -from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableHeaders -from google.cloud.websecurityscanner_v1.types.finding_addon import VulnerableParameters -from google.cloud.websecurityscanner_v1.types.finding_addon import Xss -from google.cloud.websecurityscanner_v1.types.finding_type_stats import FindingTypeStats -from google.cloud.websecurityscanner_v1.types.scan_config import ScanConfig -from google.cloud.websecurityscanner_v1.types.scan_config_error import ScanConfigError -from google.cloud.websecurityscanner_v1.types.scan_run import ScanRun -from google.cloud.websecurityscanner_v1.types.scan_run_error_trace import ScanRunErrorTrace -from google.cloud.websecurityscanner_v1.types.scan_run_warning_trace import ScanRunWarningTrace -from google.cloud.websecurityscanner_v1.types.web_security_scanner import CreateScanConfigRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import DeleteScanConfigRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetFindingRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanConfigRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import GetScanRunRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListCrawledUrlsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListFindingTypeStatsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanConfigsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import ListScanRunsResponse -from google.cloud.websecurityscanner_v1.types.web_security_scanner import StartScanRunRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import StopScanRunRequest -from google.cloud.websecurityscanner_v1.types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ('WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed deleted file mode 100644 index 8cfb5d2..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.py deleted file mode 100644 index 130eb6c..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/__init__.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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.web_security_scanner import WebSecurityScannerClient -from .services.web_security_scanner import WebSecurityScannerAsyncClient - -from .types.crawled_url import CrawledUrl -from .types.finding import Finding -from .types.finding_addon import Form -from .types.finding_addon import OutdatedLibrary -from .types.finding_addon import ViolatingResource -from .types.finding_addon import VulnerableHeaders -from .types.finding_addon import VulnerableParameters -from .types.finding_addon import Xss -from .types.finding_type_stats import FindingTypeStats -from .types.scan_config import ScanConfig -from .types.scan_config_error import ScanConfigError -from .types.scan_run import ScanRun -from .types.scan_run_error_trace import ScanRunErrorTrace -from .types.scan_run_warning_trace import ScanRunWarningTrace -from .types.web_security_scanner import CreateScanConfigRequest -from .types.web_security_scanner import DeleteScanConfigRequest -from .types.web_security_scanner import GetFindingRequest -from .types.web_security_scanner import GetScanConfigRequest -from .types.web_security_scanner import GetScanRunRequest -from .types.web_security_scanner import ListCrawledUrlsRequest -from .types.web_security_scanner import ListCrawledUrlsResponse -from .types.web_security_scanner import ListFindingsRequest -from .types.web_security_scanner import ListFindingsResponse -from .types.web_security_scanner import ListFindingTypeStatsRequest -from .types.web_security_scanner import ListFindingTypeStatsResponse -from .types.web_security_scanner import ListScanConfigsRequest -from .types.web_security_scanner import ListScanConfigsResponse -from .types.web_security_scanner import ListScanRunsRequest -from .types.web_security_scanner import ListScanRunsResponse -from .types.web_security_scanner import StartScanRunRequest -from .types.web_security_scanner import StopScanRunRequest -from .types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ( - 'WebSecurityScannerAsyncClient', -'CrawledUrl', -'CreateScanConfigRequest', -'DeleteScanConfigRequest', -'Finding', -'FindingTypeStats', -'Form', -'GetFindingRequest', -'GetScanConfigRequest', -'GetScanRunRequest', -'ListCrawledUrlsRequest', -'ListCrawledUrlsResponse', -'ListFindingTypeStatsRequest', -'ListFindingTypeStatsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListScanConfigsRequest', -'ListScanConfigsResponse', -'ListScanRunsRequest', -'ListScanRunsResponse', -'OutdatedLibrary', -'ScanConfig', -'ScanConfigError', -'ScanRun', -'ScanRunErrorTrace', -'ScanRunWarningTrace', -'StartScanRunRequest', -'StopScanRunRequest', -'UpdateScanConfigRequest', -'ViolatingResource', -'VulnerableHeaders', -'VulnerableParameters', -'WebSecurityScannerClient', -'Xss', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json deleted file mode 100644 index 2b6f23a..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/gapic_metadata.json +++ /dev/null @@ -1,153 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.websecurityscanner_v1", - "protoPackage": "google.cloud.websecurityscanner.v1", - "schema": "1.0", - "services": { - "WebSecurityScanner": { - "clients": { - "grpc": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebSecurityScannerAsyncClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed deleted file mode 100644 index 8cfb5d2..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py deleted file mode 100644 index 46b053b..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import WebSecurityScannerClient -from .async_client import WebSecurityScannerAsyncClient - -__all__ = ( - 'WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py deleted file mode 100644 index c5873e0..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/async_client.py +++ /dev/null @@ -1,992 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_addon -from google.cloud.websecurityscanner_v1.types import finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .client import WebSecurityScannerClient - - -class WebSecurityScannerAsyncClient: - """Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - """ - - _client: WebSecurityScannerClient - - DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - - finding_path = staticmethod(WebSecurityScannerClient.finding_path) - parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) - common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) - parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) - common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) - parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) - common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) - parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) - common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) - parse_common_location_path = staticmethod(WebSecurityScannerClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WebSecurityScannerClient).get_transport_class, type(WebSecurityScannerClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, WebSecurityScannerTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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, ~.WebSecurityScannerTransport]): 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 = WebSecurityScannerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_scan_config(self, - request: web_security_scanner.CreateScanConfigRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest`): - The request object. Request for the `CreateScanConfig` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.CreateScanConfigRequest(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.create_scan_config, - default_timeout=600.0, - client_info=DEFAULT_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_scan_config(self, - request: web_security_scanner.DeleteScanConfigRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest`): - The request object. Request for the `DeleteScanConfig` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.DeleteScanConfigRequest(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.delete_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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_scan_config(self, - request: web_security_scanner.GetScanConfigRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.GetScanConfigRequest`): - The request object. Request for the `GetScanConfig` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.GetScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_scan_configs(self, - request: web_security_scanner.ListScanConfigsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsAsyncPager: - r"""Lists ScanConfigs under a given project. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest`): - The request object. Request for the `ListScanConfigs` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: - Response for the ListScanConfigs method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListScanConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_scan_config(self, - request: web_security_scanner.UpdateScanConfigRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest`): - The request object. Request for the - `UpdateScanConfigRequest` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.UpdateScanConfigRequest(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.update_scan_config, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def start_scan_run(self, - request: web_security_scanner.StartScanRunRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.StartScanRunRequest`): - The request object. Request for the `StartScanRun` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.StartScanRunRequest(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.start_scan_run, - default_timeout=600.0, - client_info=DEFAULT_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_scan_run(self, - request: web_security_scanner.GetScanRunRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.GetScanRunRequest`): - The request object. Request for the `GetScanRun` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.GetScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_scan_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_scan_runs(self, - request: web_security_scanner.ListScanRunsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsAsyncPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.ListScanRunsRequest`): - The request object. Request for the `ListScanRuns` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsAsyncPager: - Response for the ListScanRuns method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.ListScanRunsRequest(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_scan_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListScanRunsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def stop_scan_run(self, - request: web_security_scanner.StopScanRunRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.StopScanRunRequest`): - The request object. Request for the `StopScanRun` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.StopScanRunRequest(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.stop_scan_run, - default_timeout=600.0, - client_info=DEFAULT_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 list_crawled_urls(self, - request: web_security_scanner.ListCrawledUrlsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsAsyncPager: - r"""List CrawledUrls under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest`): - The request object. Request for the `ListCrawledUrls` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: - Response for the ListCrawledUrls method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListCrawledUrlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_finding(self, - request: web_security_scanner.GetFindingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.GetFindingRequest`): - The request object. Request for the `GetFinding` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.GetFindingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_finding, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_findings(self, - request: web_security_scanner.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""List Findings under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.ListFindingsRequest`): - The request object. Request for the `ListFindings` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsAsyncPager: - Response for the ListFindings method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_findings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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_finding_type_stats(self, - request: web_security_scanner.ListFindingTypeStatsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest`): - The request object. Request for the - `ListFindingTypeStats` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # Create or coerce a protobuf request object. - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-websecurityscanner", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebSecurityScannerAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py deleted file mode 100644 index f43e67b..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py +++ /dev/null @@ -1,1133 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_addon -from google.cloud.websecurityscanner_v1.types import finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebSecurityScannerGrpcTransport -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport - - -class WebSecurityScannerClientMeta(type): - """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] - _transport_registry["grpc"] = WebSecurityScannerGrpcTransport - _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[WebSecurityScannerTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): - """Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "websecurityscanner.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, WebSecurityScannerTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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, WebSecurityScannerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, WebSecurityScannerTransport): - # transport is a WebSecurityScannerTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_scan_config(self, - request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.CreateScanConfigRequest, dict]): - The request object. Request for the `CreateScanConfig` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.CreateScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_scan_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_scan_config(self, - request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.DeleteScanConfigRequest, dict]): - The request object. Request for the `DeleteScanConfig` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.DeleteScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_scan_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_scan_config(self, - request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.GetScanConfigRequest, dict]): - The request object. Request for the `GetScanConfig` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.GetScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_scan_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 list_scan_configs(self, - request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsPager: - r"""Lists ScanConfigs under a given project. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest, dict]): - The request object. Request for the `ListScanConfigs` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanConfigsPager: - Response for the ListScanConfigs method. - - 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 web_security_scanner.ListScanConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_scan_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.ListScanConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_scan_config(self, - request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.UpdateScanConfigRequest, dict]): - The request object. Request for the - `UpdateScanConfigRequest` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.UpdateScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def start_scan_run(self, - request: Union[web_security_scanner.StartScanRunRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.StartScanRunRequest, dict]): - The request object. Request for the `StartScanRun` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.StartScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.start_scan_run] - - # 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_scan_run(self, - request: Union[web_security_scanner.GetScanRunRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.GetScanRunRequest, dict]): - The request object. Request for the `GetScanRun` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.GetScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_scan_run] - - # 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 list_scan_runs(self, - request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListScanRunsRequest, dict]): - The request object. Request for the `ListScanRuns` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListScanRunsPager: - Response for the ListScanRuns method. - - 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 web_security_scanner.ListScanRunsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_scan_runs] - - # 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.ListScanRunsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def stop_scan_run(self, - request: Union[web_security_scanner.StopScanRunRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.StopScanRunRequest, dict]): - The request object. Request for the `StopScanRun` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.StopScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stop_scan_run] - - # 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 list_crawled_urls(self, - request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsPager: - r"""List CrawledUrls under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest, dict]): - The request object. Request for the `ListCrawledUrls` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListCrawledUrlsPager: - Response for the ListCrawledUrls method. - - 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 web_security_scanner.ListCrawledUrlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_crawled_urls] - - # 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.ListCrawledUrlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_finding(self, - request: Union[web_security_scanner.GetFindingRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.GetFindingRequest, dict]): - The request object. Request for the `GetFinding` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.GetFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_finding] - - # 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 list_findings(self, - request: Union[web_security_scanner.ListFindingsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""List Findings under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListFindingsRequest, dict]): - The request object. Request for the `ListFindings` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.services.web_security_scanner.pagers.ListFindingsPager: - Response for the ListFindings method. - - 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 web_security_scanner.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.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_finding_type_stats(self, - request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsRequest, dict]): - The request object. Request for the - `ListFindingTypeStats` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats method. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a web_security_scanner.ListFindingTypeStatsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_finding_type_stats] - - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-websecurityscanner", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebSecurityScannerClient", -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py deleted file mode 100644 index e7efdf9..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/pagers.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner - - -class ListScanConfigsPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` - 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[..., web_security_scanner.ListScanConfigsResponse], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): - 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 = web_security_scanner.ListScanConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - for page in self.pages: - yield from page.scan_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanConfigsAsyncPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse` - 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[web_security_scanner.ListScanConfigsResponse]], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanConfigsResponse): - 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 = web_security_scanner.ListScanConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` - 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[..., web_security_scanner.ListScanRunsResponse], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): - 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 = web_security_scanner.ListScanRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - for page in self.pages: - yield from page.scan_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsAsyncPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListScanRunsResponse` - 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[web_security_scanner.ListScanRunsResponse]], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListScanRunsResponse): - 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 = web_security_scanner.ListScanRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` - 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[..., web_security_scanner.ListCrawledUrlsResponse], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): - 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 = web_security_scanner.ListCrawledUrlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - for page in self.pages: - yield from page.crawled_urls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsAsyncPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse` - 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[web_security_scanner.ListCrawledUrlsResponse]], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListCrawledUrlsResponse): - 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 = web_security_scanner.ListCrawledUrlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - async def async_generator(): - async for page in self.pages: - for response in page.crawled_urls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListFindingsResponse], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[web_security_scanner.ListFindingsResponse]], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1.types.ListFindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.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[web_security_scanner.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) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py deleted file mode 100644 index 19f4df5..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import WebSecurityScannerTransport -from .grpc import WebSecurityScannerGrpcTransport -from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] -_transport_registry['grpc'] = WebSecurityScannerGrpcTransport -_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport - -__all__ = ( - 'WebSecurityScannerTransport', - 'WebSecurityScannerGrpcTransport', - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py deleted file mode 100644 index 9ac4b7b..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/base.py +++ /dev/null @@ -1,403 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-websecurityscanner', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class WebSecurityScannerTransport(abc.ABC): - """Abstract transport class for WebSecurityScanner.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'websecurityscanner.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_scan_config: gapic_v1.method.wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: gapic_v1.method.wrap_method( - self.delete_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: gapic_v1.method.wrap_method( - self.get_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: gapic_v1.method.wrap_method( - self.list_scan_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: gapic_v1.method.wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: gapic_v1.method.wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: gapic_v1.method.wrap_method( - self.get_scan_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: gapic_v1.method.wrap_method( - self.list_scan_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: gapic_v1.method.wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: gapic_v1.method.wrap_method( - self.list_crawled_urls, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: gapic_v1.method.wrap_method( - self.get_finding, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: gapic_v1.method.wrap_method( - self.list_finding_type_stats, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Union[ - web_security_scanner.ListScanConfigsResponse, - Awaitable[web_security_scanner.ListScanConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Union[ - web_security_scanner.ListScanRunsResponse, - Awaitable[web_security_scanner.ListScanRunsResponse] - ]]: - raise NotImplementedError() - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Union[ - web_security_scanner.ListCrawledUrlsResponse, - Awaitable[web_security_scanner.ListCrawledUrlsResponse] - ]]: - raise NotImplementedError() - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Union[ - web_security_scanner.ListFindingsResponse, - Awaitable[web_security_scanner.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Union[ - web_security_scanner.ListFindingTypeStatsResponse, - Awaitable[web_security_scanner.ListFindingTypeStatsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'WebSecurityScannerTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py deleted file mode 100644 index b338a65..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc.py +++ /dev/null @@ -1,574 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - - -class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): - """gRPC backend transport for WebSecurityScanner. - - Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - - 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 = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - ~.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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - ~.ListScanConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - ~.ListScanRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - ~.ListCrawledUrlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - ~.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 'get_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - 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.websecurityscanner.v1.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - ~.ListFindingTypeStatsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - -__all__ = ( - 'WebSecurityScannerGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py deleted file mode 100644 index 7062170..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/grpc_asyncio.py +++ /dev/null @@ -1,578 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .grpc import WebSecurityScannerGrpcTransport - - -class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): - """gRPC AsyncIO backend transport for WebSecurityScanner. - - Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud. It - crawls your application, and attempts to exercise as many user - inputs and event handlers as possible. - - 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 = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - 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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Awaitable[web_security_scanner.ListScanConfigsResponse]]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - Awaitable[~.ListScanConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Awaitable[web_security_scanner.ListScanRunsResponse]]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - Awaitable[~.ListScanRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - Awaitable[~.ListCrawledUrlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - 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 'get_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Awaitable[web_security_scanner.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - 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.websecurityscanner.v1.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - Awaitable[~.ListFindingTypeStatsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - -__all__ = ( - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py deleted file mode 100644 index 36cb2b7..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/__init__.py +++ /dev/null @@ -1,102 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .crawled_url import ( - CrawledUrl, -) -from .finding import ( - Finding, -) -from .finding_addon import ( - Form, - OutdatedLibrary, - ViolatingResource, - VulnerableHeaders, - VulnerableParameters, - Xss, -) -from .finding_type_stats import ( - FindingTypeStats, -) -from .scan_config import ( - ScanConfig, -) -from .scan_config_error import ( - ScanConfigError, -) -from .scan_run import ( - ScanRun, -) -from .scan_run_error_trace import ( - ScanRunErrorTrace, -) -from .scan_run_warning_trace import ( - ScanRunWarningTrace, -) -from .web_security_scanner import ( - CreateScanConfigRequest, - DeleteScanConfigRequest, - GetFindingRequest, - GetScanConfigRequest, - GetScanRunRequest, - ListCrawledUrlsRequest, - ListCrawledUrlsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListFindingTypeStatsRequest, - ListFindingTypeStatsResponse, - ListScanConfigsRequest, - ListScanConfigsResponse, - ListScanRunsRequest, - ListScanRunsResponse, - StartScanRunRequest, - StopScanRunRequest, - UpdateScanConfigRequest, -) - -__all__ = ( - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py deleted file mode 100644 index 42e6c94..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/crawled_url.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'CrawledUrl', - }, -) - - -class CrawledUrl(proto.Message): - r"""A CrawledUrl resource represents a URL that was crawled - during a ScanRun. Web Security Scanner Service crawls the web - applications, following all links within the scope of sites, to - find the URLs to test against. - - Attributes: - http_method (str): - Output only. The http method of the request - that was used to visit the URL, in uppercase. - url (str): - Output only. The URL that was crawled. - body (str): - Output only. The body of the request that was - used to visit the URL. - """ - - http_method = proto.Field( - proto.STRING, - number=1, - ) - url = proto.Field( - proto.STRING, - number=2, - ) - body = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py deleted file mode 100644 index 12855fc..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding.py +++ /dev/null @@ -1,185 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1.types import finding_addon - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""A Finding resource represents a vulnerability instance - identified during a ScanRun. - - Attributes: - name (str): - Output only. The resource name of the - Finding. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. - The finding IDs are generated by the system. - finding_type (str): - Output only. The type of the Finding. - Detailed and up-to-date information on findings - can be found here: - https://cloud.google.com/security-command- - center/docs/how-to-remediate-web-security- - scanner-findings - severity (google.cloud.websecurityscanner_v1.types.Finding.Severity): - Output only. The severity level of the - reported vulnerability. - http_method (str): - Output only. The http method of the request - that triggered the vulnerability, in uppercase. - fuzzed_url (str): - Output only. The URL produced by the server- - ide fuzzer and used in the request that - triggered the vulnerability. - body (str): - Output only. The body of the request that - triggered the vulnerability. - description (str): - Output only. The description of the - vulnerability. - reproduction_url (str): - Output only. The URL containing human- - eadable payload that user can leverage to - reproduce the vulnerability. - frame_url (str): - Output only. If the vulnerability was - originated from nested IFrame, the immediate - parent IFrame is reported. - final_url (str): - Output only. The URL where the browser lands - when the vulnerability is detected. - tracking_id (str): - Output only. The tracking ID uniquely - identifies a vulnerability instance across - multiple ScanRuns. - form (google.cloud.websecurityscanner_v1.types.Form): - Output only. An addon containing information - reported for a vulnerability with an HTML form, - if any. - outdated_library (google.cloud.websecurityscanner_v1.types.OutdatedLibrary): - Output only. An addon containing information - about outdated libraries. - violating_resource (google.cloud.websecurityscanner_v1.types.ViolatingResource): - Output only. An addon containing detailed - information regarding any resource causing the - vulnerability such as JavaScript sources, image, - audio files, etc. - vulnerable_headers (google.cloud.websecurityscanner_v1.types.VulnerableHeaders): - Output only. An addon containing information - about vulnerable or missing HTTP headers. - vulnerable_parameters (google.cloud.websecurityscanner_v1.types.VulnerableParameters): - Output only. An addon containing information - about request parameters which were found to be - vulnerable. - xss (google.cloud.websecurityscanner_v1.types.Xss): - Output only. An addon containing information - reported for an XSS, if any. - """ - class Severity(proto.Enum): - r"""The severity level of a vulnerability.""" - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - name = proto.Field( - proto.STRING, - number=1, - ) - finding_type = proto.Field( - proto.STRING, - number=2, - ) - severity = proto.Field( - proto.ENUM, - number=17, - enum=Severity, - ) - http_method = proto.Field( - proto.STRING, - number=3, - ) - fuzzed_url = proto.Field( - proto.STRING, - number=4, - ) - body = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - reproduction_url = proto.Field( - proto.STRING, - number=7, - ) - frame_url = proto.Field( - proto.STRING, - number=8, - ) - final_url = proto.Field( - proto.STRING, - number=9, - ) - tracking_id = proto.Field( - proto.STRING, - number=10, - ) - form = proto.Field( - proto.MESSAGE, - number=16, - message=finding_addon.Form, - ) - outdated_library = proto.Field( - proto.MESSAGE, - number=11, - message=finding_addon.OutdatedLibrary, - ) - violating_resource = proto.Field( - proto.MESSAGE, - number=12, - message=finding_addon.ViolatingResource, - ) - vulnerable_headers = proto.Field( - proto.MESSAGE, - number=15, - message=finding_addon.VulnerableHeaders, - ) - vulnerable_parameters = proto.Field( - proto.MESSAGE, - number=13, - message=finding_addon.VulnerableParameters, - ) - xss = proto.Field( - proto.MESSAGE, - number=14, - message=finding_addon.Xss, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py deleted file mode 100644 index 2be0c61..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_addon.py +++ /dev/null @@ -1,206 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableParameters', - 'VulnerableHeaders', - 'Xss', - }, -) - - -class Form(proto.Message): - r"""! Information about a vulnerability with an HTML. - Attributes: - action_uri (str): - ! The URI where to send the form when it's - submitted. - fields (Sequence[str]): - ! The names of form fields related to the - vulnerability. - """ - - action_uri = proto.Field( - proto.STRING, - number=1, - ) - fields = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class OutdatedLibrary(proto.Message): - r"""Information reported for an outdated library. - Attributes: - library_name (str): - The name of the outdated library. - version (str): - The version number. - learn_more_urls (Sequence[str]): - URLs to learn more information about the - vulnerabilities in the library. - """ - - library_name = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - learn_more_urls = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ViolatingResource(proto.Message): - r"""Information regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, etc. - - Attributes: - content_type (str): - The MIME type of this resource. - resource_url (str): - URL of this violating resource. - """ - - content_type = proto.Field( - proto.STRING, - number=1, - ) - resource_url = proto.Field( - proto.STRING, - number=2, - ) - - -class VulnerableParameters(proto.Message): - r"""Information about vulnerable request parameters. - Attributes: - parameter_names (Sequence[str]): - The vulnerable parameter names. - """ - - parameter_names = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VulnerableHeaders(proto.Message): - r"""Information about vulnerable or missing HTTP Headers. - Attributes: - headers (Sequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): - List of vulnerable headers. - missing_headers (Sequence[google.cloud.websecurityscanner_v1.types.VulnerableHeaders.Header]): - List of missing headers. - """ - - class Header(proto.Message): - r"""Describes a HTTP Header. - Attributes: - name (str): - Header name. - value (str): - Header value. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.STRING, - number=2, - ) - - headers = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Header, - ) - missing_headers = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Header, - ) - - -class Xss(proto.Message): - r"""Information reported for an XSS. - Attributes: - stack_traces (Sequence[str]): - Stack traces leading to the point where the - XSS occurred. - error_message (str): - An error message generated by a javascript - breakage. - attack_vector (google.cloud.websecurityscanner_v1.types.Xss.AttackVector): - The attack vector of the payload triggering - this XSS. - stored_xss_seeding_url (str): - The reproduction url for the seeding POST - request of a Stored XSS. - """ - class AttackVector(proto.Enum): - r"""Types of XSS attack vector.""" - ATTACK_VECTOR_UNSPECIFIED = 0 - LOCAL_STORAGE = 1 - SESSION_STORAGE = 2 - WINDOW_NAME = 3 - REFERRER = 4 - FORM_INPUT = 5 - COOKIE = 6 - POST_MESSAGE = 7 - GET_PARAMETERS = 8 - URL_FRAGMENT = 9 - HTML_COMMENT = 10 - POST_PARAMETERS = 11 - PROTOCOL = 12 - STORED_XSS = 13 - SAME_ORIGIN = 14 - USER_CONTROLLABLE_URL = 15 - - stack_traces = proto.RepeatedField( - proto.STRING, - number=1, - ) - error_message = proto.Field( - proto.STRING, - number=2, - ) - attack_vector = proto.Field( - proto.ENUM, - number=3, - enum=AttackVector, - ) - stored_xss_seeding_url = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py deleted file mode 100644 index 2af70e9..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/finding_type_stats.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'FindingTypeStats', - }, -) - - -class FindingTypeStats(proto.Message): - r"""A FindingTypeStats resource represents stats regarding a - specific FindingType of Findings under a given ScanRun. - - Attributes: - finding_type (str): - Output only. The finding type associated with - the stats. - finding_count (int): - Output only. The count of findings belonging - to this finding type. - """ - - finding_type = proto.Field( - proto.STRING, - number=1, - ) - finding_count = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py deleted file mode 100644 index e906d2f..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config.py +++ /dev/null @@ -1,299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanConfig', - }, -) - - -class ScanConfig(proto.Message): - r"""A ScanConfig resource contains the configurations to launch a - scan. - - Attributes: - name (str): - The resource name of the ScanConfig. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - The ScanConfig IDs are generated by the system. - display_name (str): - Required. The user provided display name of - the ScanConfig. - max_qps (int): - The maximum QPS during scanning. A valid value ranges from 5 - to 20 inclusively. If the field is unspecified or its value - is set 0, server will default to 15. Other values outside of - [5, 20] range will be rejected with INVALID_ARGUMENT error. - starting_urls (Sequence[str]): - Required. The starting URLs from which the - scanner finds site pages. - authentication (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication): - The authentication configuration. If - specified, service will use the authentication - configuration during scanning. - user_agent (google.cloud.websecurityscanner_v1.types.ScanConfig.UserAgent): - The user agent used during scanning. - blacklist_patterns (Sequence[str]): - The excluded URL patterns as described in - https://cloud.google.com/security-command-center/docs/how-to-use-web-security-scanner#excluding_urls - schedule (google.cloud.websecurityscanner_v1.types.ScanConfig.Schedule): - The schedule of the ScanConfig. - export_to_security_command_center (google.cloud.websecurityscanner_v1.types.ScanConfig.ExportToSecurityCommandCenter): - Controls export of scan configurations and - results to Security Command Center. - risk_level (google.cloud.websecurityscanner_v1.types.ScanConfig.RiskLevel): - The risk level selected for the scan - managed_scan (bool): - Whether the scan config is managed by Web - Security Scanner, output only. - static_ip_scan (bool): - Whether the scan configuration has enabled - static IP address scan feature. If enabled, the - scanner will access applications from static IP - addresses. - """ - class UserAgent(proto.Enum): - r"""Type of user agents used for scanning.""" - USER_AGENT_UNSPECIFIED = 0 - CHROME_LINUX = 1 - CHROME_ANDROID = 2 - SAFARI_IPHONE = 3 - - class RiskLevel(proto.Enum): - r"""Scan risk levels supported by Web Security Scanner. LOW - impact scanning will minimize requests with the potential to - modify data. To achieve the maximum scan coverage, NORMAL risk - level is recommended. - """ - RISK_LEVEL_UNSPECIFIED = 0 - NORMAL = 1 - LOW = 2 - - class ExportToSecurityCommandCenter(proto.Enum): - r"""Controls export of scan configurations and results to - Security Command Center. - """ - EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - class Authentication(proto.Message): - r"""Scan authentication configuration. - Attributes: - google_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.GoogleAccount): - Authentication using a Google account. - custom_account (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.CustomAccount): - Authentication using a custom account. - iap_credential (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential): - Authentication using Identity-Aware-Proxy - (IAP). - """ - - class GoogleAccount(proto.Message): - r"""Describes authentication configuration that uses a Google - account. - - Attributes: - username (str): - Required. The user name of the Google - account. - password (str): - Required. Input only. The password of the - Google account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - """ - - username = proto.Field( - proto.STRING, - number=1, - ) - password = proto.Field( - proto.STRING, - number=2, - ) - - class CustomAccount(proto.Message): - r"""Describes authentication configuration that uses a custom - account. - - Attributes: - username (str): - Required. The user name of the custom - account. - password (str): - Required. Input only. The password of the - custom account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - login_url (str): - Required. The login form URL of the website. - """ - - username = proto.Field( - proto.STRING, - number=1, - ) - password = proto.Field( - proto.STRING, - number=2, - ) - login_url = proto.Field( - proto.STRING, - number=3, - ) - - class IapCredential(proto.Message): - r"""Describes authentication configuration for Identity-Aware- - roxy (IAP). - - Attributes: - iap_test_service_account_info (google.cloud.websecurityscanner_v1.types.ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo): - Authentication configuration when Web- - ecurity-Scanner service account is added in - Identity-Aware-Proxy (IAP) access policies. - """ - - class IapTestServiceAccountInfo(proto.Message): - r"""Describes authentication configuration when Web-Security- - canner service account is added in Identity-Aware-Proxy (IAP) - access policies. - - Attributes: - target_audience_client_id (str): - Required. Describes OAuth2 client id of - resources protected by Identity-Aware-Proxy - (IAP). - """ - - target_audience_client_id = proto.Field( - proto.STRING, - number=1, - ) - - iap_test_service_account_info = proto.Field( - proto.MESSAGE, - number=1, - oneof='iap_credentials', - message='ScanConfig.Authentication.IapCredential.IapTestServiceAccountInfo', - ) - - google_account = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication', - message='ScanConfig.Authentication.GoogleAccount', - ) - custom_account = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication', - message='ScanConfig.Authentication.CustomAccount', - ) - iap_credential = proto.Field( - proto.MESSAGE, - number=4, - oneof='authentication', - message='ScanConfig.Authentication.IapCredential', - ) - - class Schedule(proto.Message): - r"""Scan schedule configuration. - Attributes: - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - A timestamp indicates when the next run will - be scheduled. The value is refreshed by the - server after each run. If unspecified, it will - default to current server time, which means the - scan will be scheduled to start immediately. - interval_duration_days (int): - Required. The duration of time between - executions in days. - """ - - schedule_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - interval_duration_days = proto.Field( - proto.INT32, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - max_qps = proto.Field( - proto.INT32, - number=3, - ) - starting_urls = proto.RepeatedField( - proto.STRING, - number=4, - ) - authentication = proto.Field( - proto.MESSAGE, - number=5, - message=Authentication, - ) - user_agent = proto.Field( - proto.ENUM, - number=6, - enum=UserAgent, - ) - blacklist_patterns = proto.RepeatedField( - proto.STRING, - number=7, - ) - schedule = proto.Field( - proto.MESSAGE, - number=8, - message=Schedule, - ) - export_to_security_command_center = proto.Field( - proto.ENUM, - number=10, - enum=ExportToSecurityCommandCenter, - ) - risk_level = proto.Field( - proto.ENUM, - number=12, - enum=RiskLevel, - ) - managed_scan = proto.Field( - proto.BOOL, - number=13, - ) - static_ip_scan = proto.Field( - proto.BOOL, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py deleted file mode 100644 index d7d7fbf..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_config_error.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanConfigError', - }, -) - - -class ScanConfigError(proto.Message): - r"""Defines a custom error message used by CreateScanConfig and - UpdateScanConfig APIs when scan configuration validation fails. - It is also reported as part of a ScanRunErrorTrace message if - scan validation fails due to a scan configuration error. - - Attributes: - code (google.cloud.websecurityscanner_v1.types.ScanConfigError.Code): - Output only. Indicates the reason code for a - configuration failure. - field_name (str): - Output only. Indicates the full name of the ScanConfig field - that triggers this error, for example "scan_config.max_qps". - This field is provided for troubleshooting purposes only and - its actual value can change in the future. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 44 - """ - _pb_options = {'allow_alias': True} - CODE_UNSPECIFIED = 0 - OK = 0 - INTERNAL_ERROR = 1 - APPENGINE_API_BACKEND_ERROR = 2 - APPENGINE_API_NOT_ACCESSIBLE = 3 - APPENGINE_DEFAULT_HOST_MISSING = 4 - CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 - CANNOT_USE_OWNER_ACCOUNT = 7 - COMPUTE_API_BACKEND_ERROR = 8 - COMPUTE_API_NOT_ACCESSIBLE = 9 - CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 - CUSTOM_LOGIN_URL_MALFORMED = 11 - CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 - CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 - CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 - CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 - DUPLICATE_SCAN_NAME = 16 - INVALID_FIELD_VALUE = 18 - FAILED_TO_AUTHENTICATE_TO_TARGET = 19 - FINDING_TYPE_UNSPECIFIED = 20 - FORBIDDEN_TO_SCAN_COMPUTE = 21 - FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 - MALFORMED_FILTER = 22 - MALFORMED_RESOURCE_NAME = 23 - PROJECT_INACTIVE = 24 - REQUIRED_FIELD = 25 - RESOURCE_NAME_INCONSISTENT = 26 - SCAN_ALREADY_RUNNING = 27 - SCAN_NOT_RUNNING = 28 - SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 - SEED_URL_MALFORMED = 30 - SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 - SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 - SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 - SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 - SERVICE_ACCOUNT_NOT_CONFIGURED = 36 - TOO_MANY_SCANS = 37 - UNABLE_TO_RESOLVE_PROJECT_INFO = 38 - UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 - UNSUPPORTED_FILTER = 40 - UNSUPPORTED_FINDING_TYPE = 41 - UNSUPPORTED_URL_SCHEME = 42 - - code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - field_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py deleted file mode 100644 index 1097804..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run.py +++ /dev/null @@ -1,151 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRun', - }, -) - - -class ScanRun(proto.Message): - r"""A ScanRun is a output-only resource representing an actual - run of the scan. Next id: 12 - - Attributes: - name (str): - Output only. The resource name of the - ScanRun. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - The ScanRun IDs are generated by the system. - execution_state (google.cloud.websecurityscanner_v1.types.ScanRun.ExecutionState): - Output only. The execution state of the - ScanRun. - result_state (google.cloud.websecurityscanner_v1.types.ScanRun.ResultState): - Output only. The result state of the ScanRun. - This field is only available after the execution - state reaches "FINISHED". - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the ScanRun - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the ScanRun - reached termination state - that the ScanRun is - either finished or stopped by user. - urls_crawled_count (int): - Output only. The number of URLs crawled - during this ScanRun. If the scan is in progress, - the value represents the number of URLs crawled - up to now. - urls_tested_count (int): - Output only. The number of URLs tested during - this ScanRun. If the scan is in progress, the - value represents the number of URLs tested up to - now. The number of URLs tested is usually larger - than the number URLS crawled because typically a - crawled URL is tested with multiple test - payloads. - has_vulnerabilities (bool): - Output only. Whether the scan run has found - any vulnerabilities. - progress_percent (int): - Output only. The percentage of total - completion ranging from 0 to 100. If the scan is - in queue, the value is 0. If the scan is - running, the value ranges from 0 to 100. If the - scan is finished, the value is 100. - error_trace (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace): - Output only. If result_state is an ERROR, this field - provides the primary reason for scan's termination and more - details, if such are available. - warning_traces (Sequence[google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace]): - Output only. A list of warnings, if such are - encountered during this scan run. - """ - class ExecutionState(proto.Enum): - r"""Types of ScanRun execution state.""" - EXECUTION_STATE_UNSPECIFIED = 0 - QUEUED = 1 - SCANNING = 2 - FINISHED = 3 - - class ResultState(proto.Enum): - r"""Types of ScanRun result state.""" - RESULT_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - ERROR = 2 - KILLED = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - execution_state = proto.Field( - proto.ENUM, - number=2, - enum=ExecutionState, - ) - result_state = proto.Field( - proto.ENUM, - number=3, - enum=ResultState, - ) - start_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - urls_crawled_count = proto.Field( - proto.INT64, - number=6, - ) - urls_tested_count = proto.Field( - proto.INT64, - number=7, - ) - has_vulnerabilities = proto.Field( - proto.BOOL, - number=8, - ) - progress_percent = proto.Field( - proto.INT32, - number=9, - ) - error_trace = proto.Field( - proto.MESSAGE, - number=10, - message=scan_run_error_trace.ScanRunErrorTrace, - ) - warning_traces = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=scan_run_warning_trace.ScanRunWarningTrace, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py deleted file mode 100644 index ef970e5..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_error_trace.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1.types import scan_config_error as gcw_scan_config_error - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRunErrorTrace', - }, -) - - -class ScanRunErrorTrace(proto.Message): - r"""Output only. - Defines an error trace message for a ScanRun. - - Attributes: - code (google.cloud.websecurityscanner_v1.types.ScanRunErrorTrace.Code): - Output only. Indicates the error reason code. - scan_config_error (google.cloud.websecurityscanner_v1.types.ScanConfigError): - Output only. If the scan encounters SCAN_CONFIG_ISSUE error, - this field has the error message encountered during scan - configuration validation that is performed before each scan - run. - most_common_http_error_code (int): - Output only. If the scan encounters TOO_MANY_HTTP_ERRORS, - this field indicates the most common HTTP error code, if - such is available. For example, if this code is 404, the - scan has encountered too many NOT_FOUND responses. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 7 - """ - CODE_UNSPECIFIED = 0 - INTERNAL_ERROR = 1 - SCAN_CONFIG_ISSUE = 2 - AUTHENTICATION_CONFIG_ISSUE = 3 - TIMED_OUT_WHILE_SCANNING = 4 - TOO_MANY_REDIRECTS = 5 - TOO_MANY_HTTP_ERRORS = 6 - - code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - scan_config_error = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config_error.ScanConfigError, - ) - most_common_http_error_code = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py deleted file mode 100644 index e0ef98d..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/scan_run_warning_trace.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'ScanRunWarningTrace', - }, -) - - -class ScanRunWarningTrace(proto.Message): - r"""Output only. - Defines a warning trace message for ScanRun. Warning traces - provide customers with useful information that helps make the - scanning process more effective. - - Attributes: - code (google.cloud.websecurityscanner_v1.types.ScanRunWarningTrace.Code): - Output only. Indicates the warning code. - """ - class Code(proto.Enum): - r"""Output only. - Defines a warning message code. - Next id: 6 - """ - CODE_UNSPECIFIED = 0 - INSUFFICIENT_CRAWL_RESULTS = 1 - TOO_MANY_CRAWL_RESULTS = 2 - TOO_MANY_FUZZ_TASKS = 3 - BLOCKED_BY_IAP = 4 - - code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py b/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py deleted file mode 100644 index a40ea76..0000000 --- a/owl-bot-staging/v1/google/cloud/websecurityscanner_v1/types/web_security_scanner.py +++ /dev/null @@ -1,462 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_type_stats as gcw_finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1', - manifest={ - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetScanConfigRequest', - 'ListScanConfigsRequest', - 'UpdateScanConfigRequest', - 'ListScanConfigsResponse', - 'StartScanRunRequest', - 'GetScanRunRequest', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StopScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'GetFindingRequest', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - }, -) - - -class CreateScanConfigRequest(proto.Message): - r"""Request for the ``CreateScanConfig`` method. - Attributes: - parent (str): - Required. The parent resource name where the - scan is created, which should be a project - resource name in the format - 'projects/{projectId}'. - scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): - Required. The ScanConfig to be created. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - scan_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - - -class DeleteScanConfigRequest(proto.Message): - r"""Request for the ``DeleteScanConfig`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be deleted. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanConfigRequest(proto.Message): - r"""Request for the ``GetScanConfig`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanConfigsRequest(proto.Message): - r"""Request for the ``ListScanConfigs`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a project resource name in the format - 'projects/{projectId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanConfigs to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class UpdateScanConfigRequest(proto.Message): - r"""Request for the ``UpdateScanConfigRequest`` method. - Attributes: - scan_config (google.cloud.websecurityscanner_v1.types.ScanConfig): - Required. The ScanConfig to be updated. The - name field must be set to identify the resource - to be updated. The values of fields not covered - by the mask will be ignored. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - """ - - scan_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListScanConfigsResponse(proto.Message): - r"""Response for the ``ListScanConfigs`` method. - Attributes: - scan_configs (Sequence[google.cloud.websecurityscanner_v1.types.ScanConfig]): - The list of ScanConfigs returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_scan_config.ScanConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class StartScanRunRequest(proto.Message): - r"""Request for the ``StartScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be used. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanRunRequest(proto.Message): - r"""Request for the ``GetScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanRun to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanRunsRequest(proto.Message): - r"""Request for the ``ListScanRuns`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanRuns to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListScanRunsResponse(proto.Message): - r"""Response for the ``ListScanRuns`` method. - Attributes: - scan_runs (Sequence[google.cloud.websecurityscanner_v1.types.ScanRun]): - The list of ScanRuns returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_runs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=scan_run.ScanRun, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class StopScanRunRequest(proto.Message): - r"""Request for the ``StopScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanRun to - be stopped. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCrawledUrlsRequest(proto.Message): - r"""Request for the ``ListCrawledUrls`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of CrawledUrls to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCrawledUrlsResponse(proto.Message): - r"""Response for the ``ListCrawledUrls`` method. - Attributes: - crawled_urls (Sequence[google.cloud.websecurityscanner_v1.types.CrawledUrl]): - The list of CrawledUrls returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - crawled_urls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=crawled_url.CrawledUrl, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFindingRequest(proto.Message): - r"""Request for the ``GetFinding`` method. - Attributes: - name (str): - Required. The resource name of the Finding to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request for the ``ListFindings`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - filter (str): - The filter expression. The expression must be in the format: - . Supported field: 'finding_type'. Supported operator: '='. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of Findings to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response for the ``ListFindings`` method. - Attributes: - findings (Sequence[google.cloud.websecurityscanner_v1.types.Finding]): - The list of Findings returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - findings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=finding.Finding, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingTypeStatsRequest(proto.Message): - r"""Request for the ``ListFindingTypeStats`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingTypeStatsResponse(proto.Message): - r"""Response for the ``ListFindingTypeStats`` method. - Attributes: - finding_type_stats (Sequence[google.cloud.websecurityscanner_v1.types.FindingTypeStats]): - The list of FindingTypeStats returned. - """ - - finding_type_stats = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_finding_type_stats.FindingTypeStats, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index ced81d4..0000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/websecurityscanner_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py deleted file mode 100644 index 5dd19da..0000000 --- a/owl-bot-staging/v1/scripts/fixup_websecurityscanner_v1_keywords.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class websecurityscannerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', '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: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=websecurityscannerCallTransformer(), -): - """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 websecurityscanner client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index a33245a..0000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-websecurityscanner', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py b/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py deleted file mode 100644 index 1f2ecbb..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py +++ /dev/null @@ -1,3877 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerAsyncClient -from google.cloud.websecurityscanner_v1.services.web_security_scanner import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1.services.web_security_scanner import transports -from google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.websecurityscanner_v1.types import crawled_url -from google.cloud.websecurityscanner_v1.types import finding -from google.cloud.websecurityscanner_v1.types import finding_addon -from google.cloud.websecurityscanner_v1.types import finding_type_stats -from google.cloud.websecurityscanner_v1.types import scan_config -from google.cloud.websecurityscanner_v1.types import scan_run -from google.cloud.websecurityscanner_v1.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1.types import web_security_scanner -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert WebSecurityScannerClient._get_default_mtls_endpoint(None) is None - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - WebSecurityScannerClient, - WebSecurityScannerAsyncClient, -]) -def test_web_security_scanner_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WebSecurityScannerGrpcTransport, "grpc"), - (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - WebSecurityScannerClient, - WebSecurityScannerAsyncClient, -]) -def test_web_security_scanner_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -def test_web_security_scanner_client_get_transport_class(): - transport = WebSecurityScannerClient.get_transport_class() - available_transports = [ - transports.WebSecurityScannerGrpcTransport, - ] - assert transport in available_transports - - transport = WebSecurityScannerClient.get_transport_class("grpc") - assert transport == transports.WebSecurityScannerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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(WebSecurityScannerClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(WebSecurityScannerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_web_security_scanner_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_web_security_scanner_client_client_options_from_dict(): - with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebSecurityScannerClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_create_scan_config(transport: str = 'grpc', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ) - response = client.create_scan_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] == web_security_scanner.CreateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - - -def test_create_scan_config_from_dict(): - test_create_scan_config(request_type=dict) - - -def test_create_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - client.create_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest() - - -@pytest.mark.asyncio -async def test_create_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - )) - response = await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - - -@pytest.mark.asyncio -async def test_create_scan_config_async_from_dict(): - await test_create_scan_config_async(request_type=dict) - - -def test_create_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.create_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.create_scan_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_delete_scan_config(transport: str = 'grpc', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_scan_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] == web_security_scanner.DeleteScanConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_scan_config_from_dict(): - test_delete_scan_config(request_type=dict) - - -def test_delete_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - client.delete_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest() - - -@pytest.mark.asyncio -async def test_delete_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_scan_config_async_from_dict(): - await test_delete_scan_config_async(request_type=dict) - - -def test_delete_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_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_scan_config(transport: str = 'grpc', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ) - response = client.get_scan_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] == web_security_scanner.GetScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - - -def test_get_scan_config_from_dict(): - test_get_scan_config(request_type=dict) - - -def test_get_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - client.get_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest() - - -@pytest.mark.asyncio -async def test_get_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - )) - response = await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - - -@pytest.mark.asyncio -async def test_get_scan_config_async_from_dict(): - await test_get_scan_config_async(request_type=dict) - - -def test_get_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.get_scan_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_list_scan_configs(transport: str = 'grpc', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_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] == web_security_scanner.ListScanConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_configs_from_dict(): - test_list_scan_configs(request_type=dict) - - -def test_list_scan_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - client.list_scan_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest() - - -@pytest.mark.asyncio -async def test_list_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_from_dict(): - await test_list_scan_configs_async(request_type=dict) - - -def test_list_scan_configs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_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_scan_configs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - await client.list_scan_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_scan_configs_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_configs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, scan_config.ScanConfig) - for i in results) - -def test_list_scan_configs_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_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_scan_configs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_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, scan_config.ScanConfig) - for i in responses) - -@pytest.mark.asyncio -async def test_list_scan_configs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_scan_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_update_scan_config(transport: str = 'grpc', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - ) - response = client.update_scan_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] == web_security_scanner.UpdateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - - -def test_update_scan_config_from_dict(): - test_update_scan_config(request_type=dict) - - -def test_update_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - client.update_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest() - - -@pytest.mark.asyncio -async def test_update_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - managed_scan=True, - static_ip_scan=True, - )) - response = await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - assert response.managed_scan is True - assert response.static_ip_scan is True - - -@pytest.mark.asyncio -async def test_update_scan_config_async_from_dict(): - await test_update_scan_config_async(request_type=dict) - - -def test_update_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'scan_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.update_scan_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', - 'scan_config.name=scan_config.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'scan_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.update_scan_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', - 'scan_config.name=scan_config.name/value', - ) in kw['metadata'] - - -def test_start_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_start_scan_run_from_dict(): - test_start_scan_run(request_type=dict) - - -def test_start_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - client.start_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - -@pytest.mark.asyncio -async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_start_scan_run_async_from_dict(): - await test_start_scan_run_async(request_type=dict) - - -def test_start_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_start_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_scan_run(transport: str = 'grpc', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_get_scan_run_from_dict(): - test_get_scan_run(request_type=dict) - - -def test_get_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - client.get_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - -@pytest.mark.asyncio -async def test_get_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_get_scan_run_async_from_dict(): - await test_get_scan_run_async(request_type=dict) - - -def test_get_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_list_scan_runs(transport: str = 'grpc', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_runs_from_dict(): - test_list_scan_runs(request_type=dict) - - -def test_list_scan_runs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - client.list_scan_runs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - -@pytest.mark.asyncio -async def test_list_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_from_dict(): - await test_list_scan_runs_async(request_type=dict) - - -def test_list_scan_runs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_scan_runs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_scan_runs_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_runs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, scan_run.ScanRun) - for i in results) - -def test_list_scan_runs_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_runs(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_scan_runs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_runs(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, scan_run.ScanRun) - for i in responses) - -@pytest.mark.asyncio -async def test_list_scan_runs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_scan_runs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_stop_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_stop_scan_run_from_dict(): - test_stop_scan_run(request_type=dict) - - -def test_stop_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - client.stop_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - -@pytest.mark.asyncio -async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_stop_scan_run_async_from_dict(): - await test_stop_scan_run_async(request_type=dict) - - -def test_stop_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_stop_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_list_crawled_urls(transport: str = 'grpc', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_crawled_urls_from_dict(): - test_list_crawled_urls(request_type=dict) - - -def test_list_crawled_urls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - client.list_crawled_urls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_from_dict(): - await test_list_crawled_urls_async(request_type=dict) - - -def test_list_crawled_urls_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_crawled_urls_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_crawled_urls_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crawled_urls(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, crawled_url.CrawledUrl) - for i in results) - -def test_list_crawled_urls_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in responses) - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_crawled_urls(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_finding(transport: str = 'grpc', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - finding_type='finding_type_value', - severity=finding.Finding.Severity.CRITICAL, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - response = client.get_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] == web_security_scanner.GetFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -def test_get_finding_from_dict(): - test_get_finding(request_type=dict) - - -def test_get_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - client.get_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest() - - -@pytest.mark.asyncio -async def test_get_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type='finding_type_value', - severity=finding.Finding.Severity.CRITICAL, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - response = await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.asyncio -async def test_get_finding_async_from_dict(): - await test_get_finding_async(request_type=dict) - - -def test_get_finding_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_finding_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_list_findings(transport: str = 'grpc', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - ) - 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] == web_security_scanner.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' - - -def test_list_findings_from_dict(): - test_list_findings(request_type=dict) - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingsRequest() - - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - 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] == web_security_scanner.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - - -def test_list_findings_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.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 = web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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_finding_type_stats(transport: str = 'grpc', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse( - ) - response = client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -def test_list_finding_type_stats_from_dict(): - test_list_finding_type_stats(request_type=dict) - - -def test_list_finding_type_stats_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - client.list_finding_type_stats() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - response = await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async_from_dict(): - await test_list_finding_type_stats_async(request_type=dict) - - -def test_list_finding_type_stats_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_finding_type_stats_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_scan_config', - 'delete_scan_config', - 'get_scan_config', - 'list_scan_configs', - 'update_scan_config', - 'start_scan_run', - 'get_scan_run', - 'list_scan_runs', - 'stop_scan_run', - 'list_crawled_urls', - 'get_finding', - 'list_findings', - 'list_finding_type_stats', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - 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_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebSecurityScannerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebSecurityScannerClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebSecurityScannerGrpcTransport, grpc_helpers), - (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_web_security_scanner_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "websecurityscanner.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_web_security_scanner_host_no_port(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), - ) - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -def test_web_security_scanner_host_with_port(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), - ) - assert client.transport._host == 'websecurityscanner.googleapis.com:8000' - -def test_web_security_scanner_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_web_security_scanner_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_finding_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - finding = "octopus" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "project": "oyster", - "scan_config": "nudibranch", - "scan_run": "cuttlefish", - "finding": "mussel", - } - path = WebSecurityScannerClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_finding_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebSecurityScannerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = WebSecurityScannerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebSecurityScannerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = WebSecurityScannerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebSecurityScannerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = WebSecurityScannerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = WebSecurityScannerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = WebSecurityScannerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = WebSecurityScannerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = WebSecurityScannerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - transport_class = WebSecurityScannerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc deleted file mode 100644 index 6b433c1..0000000 --- a/owl-bot-staging/v1alpha/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/websecurityscanner/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in deleted file mode 100644 index 984c53e..0000000 --- a/owl-bot-staging/v1alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/websecurityscanner *.py -recursive-include google/cloud/websecurityscanner_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst deleted file mode 100644 index 4de4c10..0000000 --- a/owl-bot-staging/v1alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Websecurityscanner API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Websecurityscanner API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py deleted file mode 100644 index c393cbd..0000000 --- a/owl-bot-staging/v1alpha/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-websecurityscanner documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-websecurityscanner" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-websecurityscanner-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-websecurityscanner.tex", - u"google-cloud-websecurityscanner Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-websecurityscanner", - u"Google Cloud Websecurityscanner Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-websecurityscanner", - u"google-cloud-websecurityscanner Documentation", - author, - "google-cloud-websecurityscanner", - "GAPIC library for Google Cloud Websecurityscanner API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst deleted file mode 100644 index d13b957..0000000 --- a/owl-bot-staging/v1alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - websecurityscanner_v1alpha/services - websecurityscanner_v1alpha/types diff --git a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst deleted file mode 100644 index a4ad413..0000000 --- a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Websecurityscanner v1alpha API -======================================================== -.. toctree:: - :maxdepth: 2 - - web_security_scanner diff --git a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst deleted file mode 100644 index 0f6d569..0000000 --- a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Websecurityscanner v1alpha API -===================================================== - -.. automodule:: google.cloud.websecurityscanner_v1alpha.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst b/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst deleted file mode 100644 index 1bb5688..0000000 --- a/owl-bot-staging/v1alpha/docs/websecurityscanner_v1alpha/web_security_scanner.rst +++ /dev/null @@ -1,10 +0,0 @@ -WebSecurityScanner ------------------------------------- - -.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner - :members: - :inherited-members: - -.. automodule:: google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py deleted file mode 100644 index a25e69d..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/__init__.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.client import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient - -from google.cloud.websecurityscanner_v1alpha.types.crawled_url import CrawledUrl -from google.cloud.websecurityscanner_v1alpha.types.finding import Finding -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import OutdatedLibrary -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import ViolatingResource -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableHeaders -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import VulnerableParameters -from google.cloud.websecurityscanner_v1alpha.types.finding_addon import Xss -from google.cloud.websecurityscanner_v1alpha.types.finding_type_stats import FindingTypeStats -from google.cloud.websecurityscanner_v1alpha.types.scan_config import ScanConfig -from google.cloud.websecurityscanner_v1alpha.types.scan_run import ScanRun -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import CreateScanConfigRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import DeleteScanConfigRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetFindingRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanConfigRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import GetScanRunRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListCrawledUrlsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListFindingTypeStatsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanConfigsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import ListScanRunsResponse -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StartScanRunRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import StopScanRunRequest -from google.cloud.websecurityscanner_v1alpha.types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ('WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', - 'CrawledUrl', - 'Finding', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanRun', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed deleted file mode 100644 index 8cfb5d2..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py deleted file mode 100644 index 423e06e..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.web_security_scanner import WebSecurityScannerClient -from .services.web_security_scanner import WebSecurityScannerAsyncClient - -from .types.crawled_url import CrawledUrl -from .types.finding import Finding -from .types.finding_addon import OutdatedLibrary -from .types.finding_addon import ViolatingResource -from .types.finding_addon import VulnerableHeaders -from .types.finding_addon import VulnerableParameters -from .types.finding_addon import Xss -from .types.finding_type_stats import FindingTypeStats -from .types.scan_config import ScanConfig -from .types.scan_run import ScanRun -from .types.web_security_scanner import CreateScanConfigRequest -from .types.web_security_scanner import DeleteScanConfigRequest -from .types.web_security_scanner import GetFindingRequest -from .types.web_security_scanner import GetScanConfigRequest -from .types.web_security_scanner import GetScanRunRequest -from .types.web_security_scanner import ListCrawledUrlsRequest -from .types.web_security_scanner import ListCrawledUrlsResponse -from .types.web_security_scanner import ListFindingsRequest -from .types.web_security_scanner import ListFindingsResponse -from .types.web_security_scanner import ListFindingTypeStatsRequest -from .types.web_security_scanner import ListFindingTypeStatsResponse -from .types.web_security_scanner import ListScanConfigsRequest -from .types.web_security_scanner import ListScanConfigsResponse -from .types.web_security_scanner import ListScanRunsRequest -from .types.web_security_scanner import ListScanRunsResponse -from .types.web_security_scanner import StartScanRunRequest -from .types.web_security_scanner import StopScanRunRequest -from .types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ( - 'WebSecurityScannerAsyncClient', -'CrawledUrl', -'CreateScanConfigRequest', -'DeleteScanConfigRequest', -'Finding', -'FindingTypeStats', -'GetFindingRequest', -'GetScanConfigRequest', -'GetScanRunRequest', -'ListCrawledUrlsRequest', -'ListCrawledUrlsResponse', -'ListFindingTypeStatsRequest', -'ListFindingTypeStatsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListScanConfigsRequest', -'ListScanConfigsResponse', -'ListScanRunsRequest', -'ListScanRunsResponse', -'OutdatedLibrary', -'ScanConfig', -'ScanRun', -'StartScanRunRequest', -'StopScanRunRequest', -'UpdateScanConfigRequest', -'ViolatingResource', -'VulnerableHeaders', -'VulnerableParameters', -'WebSecurityScannerClient', -'Xss', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json deleted file mode 100644 index f43f913..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json +++ /dev/null @@ -1,153 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.websecurityscanner_v1alpha", - "protoPackage": "google.cloud.websecurityscanner.v1alpha", - "schema": "1.0", - "services": { - "WebSecurityScanner": { - "clients": { - "grpc": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebSecurityScannerAsyncClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed deleted file mode 100644 index 8cfb5d2..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py deleted file mode 100644 index 46b053b..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import WebSecurityScannerClient -from .async_client import WebSecurityScannerAsyncClient - -__all__ = ( - 'WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py deleted file mode 100644 index fbef3ec..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/async_client.py +++ /dev/null @@ -1,1314 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_addon -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .client import WebSecurityScannerClient - - -class WebSecurityScannerAsyncClient: - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - _client: WebSecurityScannerClient - - DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - - finding_path = staticmethod(WebSecurityScannerClient.finding_path) - parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) - scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) - parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) - scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) - parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) - common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) - parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) - common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) - parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) - common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) - parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) - common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) - parse_common_location_path = staticmethod(WebSecurityScannerClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WebSecurityScannerClient).get_transport_class, type(WebSecurityScannerClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, WebSecurityScannerTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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, ~.WebSecurityScannerTransport]): 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 = WebSecurityScannerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_scan_config(self, - request: web_security_scanner.CreateScanConfigRequest = None, - *, - parent: str = None, - scan_config: gcw_scan_config.ScanConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest`): - The request object. Request for the `CreateScanConfig` - method. - parent (:class:`str`): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity 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, scan_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.CreateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_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_scan_config, - default_timeout=600.0, - client_info=DEFAULT_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_scan_config(self, - request: web_security_scanner.DeleteScanConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest`): - The request object. Request for the `DeleteScanConfig` - method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.DeleteScanConfigRequest(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_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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_scan_config(self, - request: web_security_scanner.GetScanConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest`): - The request object. Request for the `GetScanConfig` - method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.GetScanConfigRequest(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_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_scan_configs(self, - request: web_security_scanner.ListScanConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsAsyncPager: - r"""Lists ScanConfigs under a given project. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest`): - The request object. Request for the `ListScanConfigs` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: - Response for the ListScanConfigs method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListScanConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_scan_config(self, - request: web_security_scanner.UpdateScanConfigRequest = None, - *, - scan_config: gcw_scan_config.ScanConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest`): - The request object. Request for the - `UpdateScanConfigRequest` method. - scan_config (:class:`google.cloud.websecurityscanner_v1alpha.types.ScanConfig`): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.UpdateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_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_scan_config, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def start_scan_run(self, - request: web_security_scanner.StartScanRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest`): - The request object. Request for the `StartScanRun` - method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.StartScanRunRequest(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.start_scan_run, - default_timeout=600.0, - client_info=DEFAULT_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_scan_run(self, - request: web_security_scanner.GetScanRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest`): - The request object. Request for the `GetScanRun` method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.GetScanRunRequest(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_scan_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_scan_runs(self, - request: web_security_scanner.ListScanRunsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsAsyncPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest`): - The request object. Request for the `ListScanRuns` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsAsyncPager: - Response for the ListScanRuns method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListScanRunsRequest(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_scan_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListScanRunsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def stop_scan_run(self, - request: web_security_scanner.StopScanRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest`): - The request object. Request for the `StopScanRun` - method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.StopScanRunRequest(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.stop_scan_run, - default_timeout=600.0, - client_info=DEFAULT_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 list_crawled_urls(self, - request: web_security_scanner.ListCrawledUrlsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsAsyncPager: - r"""List CrawledUrls under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest`): - The request object. Request for the `ListCrawledUrls` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: - Response for the ListCrawledUrls method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListCrawledUrlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_finding(self, - request: web_security_scanner.GetFindingRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest`): - The request object. Request for the `GetFinding` method. - name (:class:`str`): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.GetFindingRequest(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_finding, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_findings(self, - request: web_security_scanner.ListFindingsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""List Findings under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest`): - The request object. Request for the `ListFindings` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsAsyncPager: - Response for the ListFindings method. - - 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, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_findings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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_finding_type_stats(self, - request: web_security_scanner.ListFindingTypeStatsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest`): - The request object. Request for the - `ListFindingTypeStats` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats 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([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-websecurityscanner", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebSecurityScannerAsyncClient", -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py deleted file mode 100644 index 88ca30c..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py +++ /dev/null @@ -1,1460 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_addon -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebSecurityScannerGrpcTransport -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport - - -class WebSecurityScannerClientMeta(type): - """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] - _transport_registry["grpc"] = WebSecurityScannerGrpcTransport - _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[WebSecurityScannerTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "websecurityscanner.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_config_path(project: str,scan_config: str,) -> str: - """Returns a fully-qualified scan_config string.""" - return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - - @staticmethod - def parse_scan_config_path(path: str) -> Dict[str,str]: - """Parses a scan_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: - """Returns a fully-qualified scan_run string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - - @staticmethod - def parse_scan_run_path(path: str) -> Dict[str,str]: - """Parses a scan_run path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, WebSecurityScannerTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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, WebSecurityScannerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, WebSecurityScannerTransport): - # transport is a WebSecurityScannerTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_scan_config(self, - request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, - *, - parent: str = None, - scan_config: gcw_scan_config.ScanConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.CreateScanConfigRequest, dict]): - The request object. Request for the `CreateScanConfig` - method. - parent (str): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity 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, scan_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 web_security_scanner.CreateScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_scan_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_scan_config(self, - request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.DeleteScanConfigRequest, dict]): - The request object. Request for the `DeleteScanConfig` - method. - name (str): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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 web_security_scanner.DeleteScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(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_scan_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_scan_config(self, - request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanConfigRequest, dict]): - The request object. Request for the `GetScanConfig` - method. - name (str): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.GetScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(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_scan_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 list_scan_configs(self, - request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsPager: - r"""Lists ScanConfigs under a given project. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest, dict]): - The request object. Request for the `ListScanConfigs` - method. - parent (str): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanConfigsPager: - Response for the ListScanConfigs method. - - 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 web_security_scanner.ListScanConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_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.ListScanConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_scan_config(self, - request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, - *, - scan_config: gcw_scan_config.ScanConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.UpdateScanConfigRequest, dict]): - The request object. Request for the - `UpdateScanConfigRequest` method. - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. next - id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_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 web_security_scanner.UpdateScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_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_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def start_scan_run(self, - request: Union[web_security_scanner.StartScanRunRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.StartScanRunRequest, dict]): - The request object. Request for the `StartScanRun` - method. - name (str): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.StartScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(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.start_scan_run] - - # 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_scan_run(self, - request: Union[web_security_scanner.GetScanRunRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.GetScanRunRequest, dict]): - The request object. Request for the `GetScanRun` method. - name (str): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.GetScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(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_scan_run] - - # 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 list_scan_runs(self, - request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest, dict]): - The request object. Request for the `ListScanRuns` - method. - parent (str): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListScanRunsPager: - Response for the ListScanRuns method. - - 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 web_security_scanner.ListScanRunsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # 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.ListScanRunsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def stop_scan_run(self, - request: Union[web_security_scanner.StopScanRunRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.StopScanRunRequest, dict]): - The request object. Request for the `StopScanRun` - method. - name (str): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.StopScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(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.stop_scan_run] - - # 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 list_crawled_urls(self, - request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsPager: - r"""List CrawledUrls under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest, dict]): - The request object. Request for the `ListCrawledUrls` - method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListCrawledUrlsPager: - Response for the ListCrawledUrls method. - - 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 web_security_scanner.ListCrawledUrlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # 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.ListCrawledUrlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_finding(self, - request: Union[web_security_scanner.GetFindingRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.GetFindingRequest, dict]): - The request object. Request for the `GetFinding` method. - name (str): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.GetFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(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_finding] - - # 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 list_findings(self, - request: Union[web_security_scanner.ListFindingsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""List Findings under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest, dict]): - The request object. Request for the `ListFindings` - method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.pagers.ListFindingsPager: - Response for the ListFindings method. - - 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, filter]) - if request is 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 web_security_scanner.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_finding_type_stats(self, - request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsRequest, dict]): - The request object. Request for the - `ListFindingTypeStats` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1alpha.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats 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([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 web_security_scanner.ListFindingTypeStatsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-websecurityscanner", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebSecurityScannerClient", -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py deleted file mode 100644 index c3acaf3..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/pagers.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner - - -class ListScanConfigsPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` - 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[..., web_security_scanner.ListScanConfigsResponse], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): - 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 = web_security_scanner.ListScanConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - for page in self.pages: - yield from page.scan_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanConfigsAsyncPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse` - 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[web_security_scanner.ListScanConfigsResponse]], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanConfigsResponse): - 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 = web_security_scanner.ListScanConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` - 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[..., web_security_scanner.ListScanRunsResponse], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): - 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 = web_security_scanner.ListScanRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - for page in self.pages: - yield from page.scan_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsAsyncPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse` - 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[web_security_scanner.ListScanRunsResponse]], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListScanRunsResponse): - 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 = web_security_scanner.ListScanRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` - 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[..., web_security_scanner.ListCrawledUrlsResponse], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): - 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 = web_security_scanner.ListCrawledUrlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - for page in self.pages: - yield from page.crawled_urls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsAsyncPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse` - 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[web_security_scanner.ListCrawledUrlsResponse]], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListCrawledUrlsResponse): - 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 = web_security_scanner.ListCrawledUrlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - async def async_generator(): - async for page in self.pages: - for response in page.crawled_urls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListFindingsResponse], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[web_security_scanner.ListFindingsResponse]], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1alpha.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1alpha.types.ListFindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.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[web_security_scanner.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) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py deleted file mode 100644 index 19f4df5..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import WebSecurityScannerTransport -from .grpc import WebSecurityScannerGrpcTransport -from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] -_transport_registry['grpc'] = WebSecurityScannerGrpcTransport -_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport - -__all__ = ( - 'WebSecurityScannerTransport', - 'WebSecurityScannerGrpcTransport', - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py deleted file mode 100644 index 466c6ae..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/base.py +++ /dev/null @@ -1,404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-websecurityscanner', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class WebSecurityScannerTransport(abc.ABC): - """Abstract transport class for WebSecurityScanner.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'websecurityscanner.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_scan_config: gapic_v1.method.wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: gapic_v1.method.wrap_method( - self.delete_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: gapic_v1.method.wrap_method( - self.get_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: gapic_v1.method.wrap_method( - self.list_scan_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: gapic_v1.method.wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: gapic_v1.method.wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: gapic_v1.method.wrap_method( - self.get_scan_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: gapic_v1.method.wrap_method( - self.list_scan_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: gapic_v1.method.wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: gapic_v1.method.wrap_method( - self.list_crawled_urls, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: gapic_v1.method.wrap_method( - self.get_finding, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: gapic_v1.method.wrap_method( - self.list_finding_type_stats, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Union[ - web_security_scanner.ListScanConfigsResponse, - Awaitable[web_security_scanner.ListScanConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Union[ - web_security_scanner.ListScanRunsResponse, - Awaitable[web_security_scanner.ListScanRunsResponse] - ]]: - raise NotImplementedError() - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Union[ - web_security_scanner.ListCrawledUrlsResponse, - Awaitable[web_security_scanner.ListCrawledUrlsResponse] - ]]: - raise NotImplementedError() - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Union[ - web_security_scanner.ListFindingsResponse, - Awaitable[web_security_scanner.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Union[ - web_security_scanner.ListFindingTypeStatsResponse, - Awaitable[web_security_scanner.ListFindingTypeStatsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'WebSecurityScannerTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py deleted file mode 100644 index f8cf97a..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc.py +++ /dev/null @@ -1,575 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - - -class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): - """gRPC backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - 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 = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - ~.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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - ~.ListScanConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - ~.ListScanRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - ~.ListCrawledUrlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - ~.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 'get_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - 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.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - ~.ListFindingTypeStatsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - -__all__ = ( - 'WebSecurityScannerGrpcTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py deleted file mode 100644 index ddeed45..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py +++ /dev/null @@ -1,579 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .grpc import WebSecurityScannerGrpcTransport - - -class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): - """gRPC AsyncIO backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - 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 = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - 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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Awaitable[web_security_scanner.ListScanConfigsResponse]]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - Awaitable[~.ListScanConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Awaitable[web_security_scanner.ListScanRunsResponse]]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - Awaitable[~.ListScanRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - Awaitable[~.ListCrawledUrlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - 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 'get_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Awaitable[web_security_scanner.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - 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.websecurityscanner.v1alpha.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - Awaitable[~.ListFindingTypeStatsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1alpha.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - -__all__ = ( - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.py deleted file mode 100644 index c8502b8..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/__init__.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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .crawled_url import ( - CrawledUrl, -) -from .finding import ( - Finding, -) -from .finding_addon import ( - OutdatedLibrary, - ViolatingResource, - VulnerableHeaders, - VulnerableParameters, - Xss, -) -from .finding_type_stats import ( - FindingTypeStats, -) -from .scan_config import ( - ScanConfig, -) -from .scan_run import ( - ScanRun, -) -from .web_security_scanner import ( - CreateScanConfigRequest, - DeleteScanConfigRequest, - GetFindingRequest, - GetScanConfigRequest, - GetScanRunRequest, - ListCrawledUrlsRequest, - ListCrawledUrlsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListFindingTypeStatsRequest, - ListFindingTypeStatsResponse, - ListScanConfigsRequest, - ListScanConfigsResponse, - ListScanRunsRequest, - ListScanRunsResponse, - StartScanRunRequest, - StopScanRunRequest, - UpdateScanConfigRequest, -) - -__all__ = ( - 'CrawledUrl', - 'Finding', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanRun', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py deleted file mode 100644 index 6b6ae8e..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/crawled_url.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'CrawledUrl', - }, -) - - -class CrawledUrl(proto.Message): - r"""A CrawledUrl resource represents a URL that was crawled - during a ScanRun. Web Security Scanner Service crawls the web - applications, following all links within the scope of sites, to - find the URLs to test against. - - Attributes: - http_method (str): - Output only. The http method of the request - that was used to visit the URL, in uppercase. - url (str): - Output only. The URL that was crawled. - body (str): - Output only. The body of the request that was - used to visit the URL. - """ - - http_method = proto.Field( - proto.STRING, - number=1, - ) - url = proto.Field( - proto.STRING, - number=2, - ) - body = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py deleted file mode 100644 index 8fad051..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding_addon - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""A Finding resource represents a vulnerability instance - identified during a ScanRun. - - Attributes: - name (str): - The resource name of the Finding. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. - The finding IDs are generated by the system. - finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): - The type of the Finding. - http_method (str): - The http method of the request that triggered - the vulnerability, in uppercase. - fuzzed_url (str): - The URL produced by the server-side fuzzer - and used in the request that triggered the - vulnerability. - body (str): - The body of the request that triggered the - vulnerability. - description (str): - The description of the vulnerability. - reproduction_url (str): - The URL containing human-readable payload - that user can leverage to reproduce the - vulnerability. - frame_url (str): - If the vulnerability was originated from - nested IFrame, the immediate parent IFrame is - reported. - final_url (str): - The URL where the browser lands when the - vulnerability is detected. - tracking_id (str): - The tracking ID uniquely identifies a - vulnerability instance across multiple ScanRuns. - outdated_library (google.cloud.websecurityscanner_v1alpha.types.OutdatedLibrary): - An addon containing information about - outdated libraries. - violating_resource (google.cloud.websecurityscanner_v1alpha.types.ViolatingResource): - An addon containing detailed information - regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, - etc. - vulnerable_headers (google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders): - An addon containing information about - vulnerable or missing HTTP headers. - vulnerable_parameters (google.cloud.websecurityscanner_v1alpha.types.VulnerableParameters): - An addon containing information about request - parameters which were found to be vulnerable. - xss (google.cloud.websecurityscanner_v1alpha.types.Xss): - An addon containing information reported for - an XSS, if any. - """ - class FindingType(proto.Enum): - r"""Types of Findings.""" - FINDING_TYPE_UNSPECIFIED = 0 - MIXED_CONTENT = 1 - OUTDATED_LIBRARY = 2 - ROSETTA_FLASH = 5 - XSS_CALLBACK = 3 - XSS_ERROR = 4 - CLEAR_TEXT_PASSWORD = 6 - INVALID_CONTENT_TYPE = 7 - XSS_ANGULAR_CALLBACK = 8 - INVALID_HEADER = 9 - MISSPELLED_SECURITY_HEADER_NAME = 10 - MISMATCHING_SECURITY_HEADER_VALUES = 11 - - name = proto.Field( - proto.STRING, - number=1, - ) - finding_type = proto.Field( - proto.ENUM, - number=2, - enum=FindingType, - ) - http_method = proto.Field( - proto.STRING, - number=3, - ) - fuzzed_url = proto.Field( - proto.STRING, - number=4, - ) - body = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - reproduction_url = proto.Field( - proto.STRING, - number=7, - ) - frame_url = proto.Field( - proto.STRING, - number=8, - ) - final_url = proto.Field( - proto.STRING, - number=9, - ) - tracking_id = proto.Field( - proto.STRING, - number=10, - ) - outdated_library = proto.Field( - proto.MESSAGE, - number=11, - message=finding_addon.OutdatedLibrary, - ) - violating_resource = proto.Field( - proto.MESSAGE, - number=12, - message=finding_addon.ViolatingResource, - ) - vulnerable_headers = proto.Field( - proto.MESSAGE, - number=15, - message=finding_addon.VulnerableHeaders, - ) - vulnerable_parameters = proto.Field( - proto.MESSAGE, - number=13, - message=finding_addon.VulnerableParameters, - ) - xss = proto.Field( - proto.MESSAGE, - number=14, - message=finding_addon.Xss, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py deleted file mode 100644 index ec36cd1..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_addon.py +++ /dev/null @@ -1,151 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableParameters', - 'VulnerableHeaders', - 'Xss', - }, -) - - -class OutdatedLibrary(proto.Message): - r"""Information reported for an outdated library. - Attributes: - library_name (str): - The name of the outdated library. - version (str): - The version number. - learn_more_urls (Sequence[str]): - URLs to learn more information about the - vulnerabilities in the library. - """ - - library_name = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - learn_more_urls = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ViolatingResource(proto.Message): - r"""Information regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, etc. - - Attributes: - content_type (str): - The MIME type of this resource. - resource_url (str): - URL of this violating resource. - """ - - content_type = proto.Field( - proto.STRING, - number=1, - ) - resource_url = proto.Field( - proto.STRING, - number=2, - ) - - -class VulnerableParameters(proto.Message): - r"""Information about vulnerable request parameters. - Attributes: - parameter_names (Sequence[str]): - The vulnerable parameter names. - """ - - parameter_names = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VulnerableHeaders(proto.Message): - r"""Information about vulnerable or missing HTTP Headers. - Attributes: - headers (Sequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): - List of vulnerable headers. - missing_headers (Sequence[google.cloud.websecurityscanner_v1alpha.types.VulnerableHeaders.Header]): - List of missing headers. - """ - - class Header(proto.Message): - r"""Describes a HTTP Header. - Attributes: - name (str): - Header name. - value (str): - Header value. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.STRING, - number=2, - ) - - headers = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Header, - ) - missing_headers = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Header, - ) - - -class Xss(proto.Message): - r"""Information reported for an XSS. - Attributes: - stack_traces (Sequence[str]): - Stack traces leading to the point where the - XSS occurred. - error_message (str): - An error message generated by a javascript - breakage. - """ - - stack_traces = proto.RepeatedField( - proto.STRING, - number=1, - ) - error_message = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py deleted file mode 100644 index 12f5ad8..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/finding_type_stats.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import finding - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'FindingTypeStats', - }, -) - - -class FindingTypeStats(proto.Message): - r"""A FindingTypeStats resource represents stats regarding a - specific FindingType of Findings under a given ScanRun. - - Attributes: - finding_type (google.cloud.websecurityscanner_v1alpha.types.Finding.FindingType): - The finding type associated with the stats. - finding_count (int): - The count of findings belonging to this - finding type. - """ - - finding_type = proto.Field( - proto.ENUM, - number=1, - enum=finding.Finding.FindingType, - ) - finding_count = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py deleted file mode 100644 index 03adc0e..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_config.py +++ /dev/null @@ -1,229 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'ScanConfig', - }, -) - - -class ScanConfig(proto.Message): - r"""A ScanConfig resource contains the configurations to launch a - scan. next id: 12 - - Attributes: - name (str): - The resource name of the ScanConfig. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - The ScanConfig IDs are generated by the system. - display_name (str): - Required. The user provided display name of - the ScanConfig. - max_qps (int): - The maximum QPS during scanning. A valid value ranges from 5 - to 20 inclusively. If the field is unspecified or its value - is set 0, server will default to 15. Other values outside of - [5, 20] range will be rejected with INVALID_ARGUMENT error. - starting_urls (Sequence[str]): - Required. The starting URLs from which the - scanner finds site pages. - authentication (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication): - The authentication configuration. If - specified, service will use the authentication - configuration during scanning. - user_agent (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.UserAgent): - The user agent used during scanning. - blacklist_patterns (Sequence[str]): - The blacklist URL patterns as described in - https://cloud.google.com/security- - scanner/docs/excluded-urls - schedule (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Schedule): - The schedule of the ScanConfig. - target_platforms (Sequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig.TargetPlatform]): - Set of Cloud Platforms targeted by the scan. If empty, - APP_ENGINE will be used as a default. - latest_run (google.cloud.websecurityscanner_v1alpha.types.ScanRun): - Latest ScanRun if available. - """ - class UserAgent(proto.Enum): - r"""Type of user agents used for scanning.""" - USER_AGENT_UNSPECIFIED = 0 - CHROME_LINUX = 1 - CHROME_ANDROID = 2 - SAFARI_IPHONE = 3 - - class TargetPlatform(proto.Enum): - r"""Cloud platforms supported by Cloud Web Security Scanner.""" - TARGET_PLATFORM_UNSPECIFIED = 0 - APP_ENGINE = 1 - COMPUTE = 2 - - class Authentication(proto.Message): - r"""Scan authentication configuration. - Attributes: - google_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.GoogleAccount): - Authentication using a Google account. - custom_account (google.cloud.websecurityscanner_v1alpha.types.ScanConfig.Authentication.CustomAccount): - Authentication using a custom account. - """ - - class GoogleAccount(proto.Message): - r"""Describes authentication configuration that uses a Google - account. - - Attributes: - username (str): - Required. The user name of the Google - account. - password (str): - Required. Input only. The password of the - Google account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - """ - - username = proto.Field( - proto.STRING, - number=1, - ) - password = proto.Field( - proto.STRING, - number=2, - ) - - class CustomAccount(proto.Message): - r"""Describes authentication configuration that uses a custom - account. - - Attributes: - username (str): - Required. The user name of the custom - account. - password (str): - Required. Input only. The password of the - custom account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - login_url (str): - Required. The login form URL of the website. - """ - - username = proto.Field( - proto.STRING, - number=1, - ) - password = proto.Field( - proto.STRING, - number=2, - ) - login_url = proto.Field( - proto.STRING, - number=3, - ) - - google_account = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication', - message='ScanConfig.Authentication.GoogleAccount', - ) - custom_account = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication', - message='ScanConfig.Authentication.CustomAccount', - ) - - class Schedule(proto.Message): - r"""Scan schedule configuration. - Attributes: - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - A timestamp indicates when the next run will - be scheduled. The value is refreshed by the - server after each run. If unspecified, it will - default to current server time, which means the - scan will be scheduled to start immediately. - interval_duration_days (int): - Required. The duration of time between - executions in days. - """ - - schedule_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - interval_duration_days = proto.Field( - proto.INT32, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - max_qps = proto.Field( - proto.INT32, - number=3, - ) - starting_urls = proto.RepeatedField( - proto.STRING, - number=4, - ) - authentication = proto.Field( - proto.MESSAGE, - number=5, - message=Authentication, - ) - user_agent = proto.Field( - proto.ENUM, - number=6, - enum=UserAgent, - ) - blacklist_patterns = proto.RepeatedField( - proto.STRING, - number=7, - ) - schedule = proto.Field( - proto.MESSAGE, - number=8, - message=Schedule, - ) - target_platforms = proto.RepeatedField( - proto.ENUM, - number=9, - enum=TargetPlatform, - ) - latest_run = proto.Field( - proto.MESSAGE, - number=11, - message=scan_run.ScanRun, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py deleted file mode 100644 index 310b999..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/scan_run.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'ScanRun', - }, -) - - -class ScanRun(proto.Message): - r"""A ScanRun is a output-only resource representing an actual - run of the scan. - - Attributes: - name (str): - The resource name of the ScanRun. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - The ScanRun IDs are generated by the system. - execution_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ExecutionState): - The execution state of the ScanRun. - result_state (google.cloud.websecurityscanner_v1alpha.types.ScanRun.ResultState): - The result state of the ScanRun. This field - is only available after the execution state - reaches "FINISHED". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun reached - termination state - that the ScanRun is either - finished or stopped by user. - urls_crawled_count (int): - The number of URLs crawled during this - ScanRun. If the scan is in progress, the value - represents the number of URLs crawled up to now. - urls_tested_count (int): - The number of URLs tested during this - ScanRun. If the scan is in progress, the value - represents the number of URLs tested up to now. - The number of URLs tested is usually larger than - the number URLS crawled because typically a - crawled URL is tested with multiple test - payloads. - has_vulnerabilities (bool): - Whether the scan run has found any - vulnerabilities. - progress_percent (int): - The percentage of total completion ranging - from 0 to 100. If the scan is in queue, the - value is 0. If the scan is running, the value - ranges from 0 to 100. If the scan is finished, - the value is 100. - """ - class ExecutionState(proto.Enum): - r"""Types of ScanRun execution state.""" - EXECUTION_STATE_UNSPECIFIED = 0 - QUEUED = 1 - SCANNING = 2 - FINISHED = 3 - - class ResultState(proto.Enum): - r"""Types of ScanRun result state.""" - RESULT_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - ERROR = 2 - KILLED = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - execution_state = proto.Field( - proto.ENUM, - number=2, - enum=ExecutionState, - ) - result_state = proto.Field( - proto.ENUM, - number=3, - enum=ResultState, - ) - start_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - urls_crawled_count = proto.Field( - proto.INT64, - number=6, - ) - urls_tested_count = proto.Field( - proto.INT64, - number=7, - ) - has_vulnerabilities = proto.Field( - proto.BOOL, - number=8, - ) - progress_percent = proto.Field( - proto.INT32, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py b/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py deleted file mode 100644 index 5191f21..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/websecurityscanner_v1alpha/types/web_security_scanner.py +++ /dev/null @@ -1,463 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats as gcw_finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1alpha', - manifest={ - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetScanConfigRequest', - 'ListScanConfigsRequest', - 'UpdateScanConfigRequest', - 'ListScanConfigsResponse', - 'StartScanRunRequest', - 'GetScanRunRequest', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StopScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'GetFindingRequest', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - }, -) - - -class CreateScanConfigRequest(proto.Message): - r"""Request for the ``CreateScanConfig`` method. - Attributes: - parent (str): - Required. The parent resource name where the - scan is created, which should be a project - resource name in the format - 'projects/{projectId}'. - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be created. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - scan_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - - -class DeleteScanConfigRequest(proto.Message): - r"""Request for the ``DeleteScanConfig`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be deleted. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanConfigRequest(proto.Message): - r"""Request for the ``GetScanConfig`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanConfigsRequest(proto.Message): - r"""Request for the ``ListScanConfigs`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a project resource name in the format - 'projects/{projectId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanConfigs to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class UpdateScanConfigRequest(proto.Message): - r"""Request for the ``UpdateScanConfigRequest`` method. - Attributes: - scan_config (google.cloud.websecurityscanner_v1alpha.types.ScanConfig): - Required. The ScanConfig to be updated. The - name field must be set to identify the resource - to be updated. The values of fields not covered - by the mask will be ignored. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - """ - - scan_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListScanConfigsResponse(proto.Message): - r"""Response for the ``ListScanConfigs`` method. - Attributes: - scan_configs (Sequence[google.cloud.websecurityscanner_v1alpha.types.ScanConfig]): - The list of ScanConfigs returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_scan_config.ScanConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class StartScanRunRequest(proto.Message): - r"""Request for the ``StartScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be used. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanRunRequest(proto.Message): - r"""Request for the ``GetScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanRun to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanRunsRequest(proto.Message): - r"""Request for the ``ListScanRuns`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanRuns to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListScanRunsResponse(proto.Message): - r"""Response for the ``ListScanRuns`` method. - Attributes: - scan_runs (Sequence[google.cloud.websecurityscanner_v1alpha.types.ScanRun]): - The list of ScanRuns returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_runs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=scan_run.ScanRun, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class StopScanRunRequest(proto.Message): - r"""Request for the ``StopScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanRun to - be stopped. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCrawledUrlsRequest(proto.Message): - r"""Request for the ``ListCrawledUrls`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of CrawledUrls to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCrawledUrlsResponse(proto.Message): - r"""Response for the ``ListCrawledUrls`` method. - Attributes: - crawled_urls (Sequence[google.cloud.websecurityscanner_v1alpha.types.CrawledUrl]): - The list of CrawledUrls returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - crawled_urls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=crawled_url.CrawledUrl, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFindingRequest(proto.Message): - r"""Request for the ``GetFinding`` method. - Attributes: - name (str): - Required. The resource name of the Finding to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request for the ``ListFindings`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - filter (str): - Required. The filter expression. The expression must be in - the format: . Supported field: 'finding_type'. Supported - operator: '='. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of Findings to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response for the ``ListFindings`` method. - Attributes: - findings (Sequence[google.cloud.websecurityscanner_v1alpha.types.Finding]): - The list of Findings returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - findings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=finding.Finding, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingTypeStatsRequest(proto.Message): - r"""Request for the ``ListFindingTypeStats`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingTypeStatsResponse(proto.Message): - r"""Response for the ``ListFindingTypeStats`` method. - Attributes: - finding_type_stats (Sequence[google.cloud.websecurityscanner_v1alpha.types.FindingTypeStats]): - The list of FindingTypeStats returned. - """ - - finding_type_stats = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_finding_type_stats.FindingTypeStats, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py deleted file mode 100644 index 16bdd22..0000000 --- a/owl-bot-staging/v1alpha/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/websecurityscanner_v1alpha/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py deleted file mode 100644 index 5dd19da..0000000 --- a/owl-bot-staging/v1alpha/scripts/fixup_websecurityscanner_v1alpha_keywords.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class websecurityscannerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', '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: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=websecurityscannerCallTransformer(), -): - """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 websecurityscanner client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py deleted file mode 100644 index a33245a..0000000 --- a/owl-bot-staging/v1alpha/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-websecurityscanner', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py b/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py deleted file mode 100644 index 71916a3..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py +++ /dev/null @@ -1,4934 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerAsyncClient -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import transports -from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.websecurityscanner_v1alpha.types import crawled_url -from google.cloud.websecurityscanner_v1alpha.types import finding -from google.cloud.websecurityscanner_v1alpha.types import finding_addon -from google.cloud.websecurityscanner_v1alpha.types import finding_type_stats -from google.cloud.websecurityscanner_v1alpha.types import scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1alpha.types import scan_run -from google.cloud.websecurityscanner_v1alpha.types import web_security_scanner -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert WebSecurityScannerClient._get_default_mtls_endpoint(None) is None - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - WebSecurityScannerClient, - WebSecurityScannerAsyncClient, -]) -def test_web_security_scanner_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WebSecurityScannerGrpcTransport, "grpc"), - (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - WebSecurityScannerClient, - WebSecurityScannerAsyncClient, -]) -def test_web_security_scanner_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -def test_web_security_scanner_client_get_transport_class(): - transport = WebSecurityScannerClient.get_transport_class() - available_transports = [ - transports.WebSecurityScannerGrpcTransport, - ] - assert transport in available_transports - - transport = WebSecurityScannerClient.get_transport_class("grpc") - assert transport == transports.WebSecurityScannerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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(WebSecurityScannerClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(WebSecurityScannerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_web_security_scanner_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_web_security_scanner_client_client_options_from_dict(): - with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebSecurityScannerClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_create_scan_config(transport: str = 'grpc', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - response = client.create_scan_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] == web_security_scanner.CreateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -def test_create_scan_config_from_dict(): - test_create_scan_config(request_type=dict) - - -def test_create_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - client.create_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest() - - -@pytest.mark.asyncio -async def test_create_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - response = await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.asyncio -async def test_create_scan_config_async_from_dict(): - await test_create_scan_config_async(request_type=dict) - - -def test_create_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.create_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.create_scan_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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') - - -def test_create_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') - - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -def test_delete_scan_config(transport: str = 'grpc', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_scan_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] == web_security_scanner.DeleteScanConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_scan_config_from_dict(): - test_delete_scan_config(request_type=dict) - - -def test_delete_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - client.delete_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest() - - -@pytest.mark.asyncio -async def test_delete_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_scan_config_async_from_dict(): - await test_delete_scan_config_async(request_type=dict) - - -def test_delete_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -def test_get_scan_config(transport: str = 'grpc', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - response = client.get_scan_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] == web_security_scanner.GetScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -def test_get_scan_config_from_dict(): - test_get_scan_config(request_type=dict) - - -def test_get_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - client.get_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest() - - -@pytest.mark.asyncio -async def test_get_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - response = await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.asyncio -async def test_get_scan_config_async_from_dict(): - await test_get_scan_config_async(request_type=dict) - - -def test_get_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.get_scan_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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -def test_list_scan_configs(transport: str = 'grpc', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_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] == web_security_scanner.ListScanConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_configs_from_dict(): - test_list_scan_configs(request_type=dict) - - -def test_list_scan_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - client.list_scan_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest() - - -@pytest.mark.asyncio -async def test_list_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_from_dict(): - await test_list_scan_configs_async(request_type=dict) - - -def test_list_scan_configs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_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_scan_configs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - await client.list_scan_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_scan_configs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_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_scan_configs_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_scan_configs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_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_scan_configs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -def test_list_scan_configs_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_configs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, scan_config.ScanConfig) - for i in results) - -def test_list_scan_configs_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_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_scan_configs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_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, scan_config.ScanConfig) - for i in responses) - -@pytest.mark.asyncio -async def test_list_scan_configs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_scan_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_update_scan_config(transport: str = 'grpc', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - ) - response = client.update_scan_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] == web_security_scanner.UpdateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -def test_update_scan_config_from_dict(): - test_update_scan_config(request_type=dict) - - -def test_update_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - client.update_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest() - - -@pytest.mark.asyncio -async def test_update_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - )) - response = await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - - -@pytest.mark.asyncio -async def test_update_scan_config_async_from_dict(): - await test_update_scan_config_async(request_type=dict) - - -def test_update_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'scan_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.update_scan_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', - 'scan_config.name=scan_config.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'scan_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.update_scan_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', - 'scan_config.name=scan_config.name/value', - ) in kw['metadata'] - - -def test_update_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_start_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_start_scan_run_from_dict(): - test_start_scan_run(request_type=dict) - - -def test_start_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - client.start_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - -@pytest.mark.asyncio -async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_start_scan_run_async_from_dict(): - await test_start_scan_run_async(request_type=dict) - - -def test_start_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_start_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_start_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_scan_run( - 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_start_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_start_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_scan_run( - 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_start_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -def test_get_scan_run(transport: str = 'grpc', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_get_scan_run_from_dict(): - test_get_scan_run(request_type=dict) - - -def test_get_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - client.get_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - -@pytest.mark.asyncio -async def test_get_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_get_scan_run_async_from_dict(): - await test_get_scan_run_async(request_type=dict) - - -def test_get_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_run( - 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_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_run( - 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_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -def test_list_scan_runs(transport: str = 'grpc', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_runs_from_dict(): - test_list_scan_runs(request_type=dict) - - -def test_list_scan_runs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - client.list_scan_runs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - -@pytest.mark.asyncio -async def test_list_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_from_dict(): - await test_list_scan_runs_async(request_type=dict) - - -def test_list_scan_runs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_scan_runs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_scan_runs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_runs( - 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_scan_runs_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_scan_runs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_runs( - 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_scan_runs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -def test_list_scan_runs_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_runs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, scan_run.ScanRun) - for i in results) - -def test_list_scan_runs_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_runs(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_scan_runs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_runs(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, scan_run.ScanRun) - for i in responses) - -@pytest.mark.asyncio -async def test_list_scan_runs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_scan_runs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_stop_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_stop_scan_run_from_dict(): - test_stop_scan_run(request_type=dict) - - -def test_stop_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - client.stop_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - -@pytest.mark.asyncio -async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_stop_scan_run_async_from_dict(): - await test_stop_scan_run_async(request_type=dict) - - -def test_stop_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_stop_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_stop_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_scan_run( - 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_stop_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_stop_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_scan_run( - 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_stop_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -def test_list_crawled_urls(transport: str = 'grpc', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_crawled_urls_from_dict(): - test_list_crawled_urls(request_type=dict) - - -def test_list_crawled_urls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - client.list_crawled_urls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_from_dict(): - await test_list_crawled_urls_async(request_type=dict) - - -def test_list_crawled_urls_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_crawled_urls_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_crawled_urls_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crawled_urls( - 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_crawled_urls_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_crawled_urls_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crawled_urls( - 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_crawled_urls_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -def test_list_crawled_urls_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crawled_urls(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, crawled_url.CrawledUrl) - for i in results) - -def test_list_crawled_urls_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in responses) - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_crawled_urls(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_finding(transport: str = 'grpc', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - finding_type=finding.Finding.FindingType.MIXED_CONTENT, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - response = client.get_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] == web_security_scanner.GetFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -def test_get_finding_from_dict(): - test_get_finding(request_type=dict) - - -def test_get_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - client.get_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest() - - -@pytest.mark.asyncio -async def test_get_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type=finding.Finding.FindingType.MIXED_CONTENT, - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - response = await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.asyncio -async def test_get_finding_async_from_dict(): - await test_get_finding_async(request_type=dict) - - -def test_get_finding_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_finding_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_finding_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__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.get_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].name == 'name_value' - - -def test_get_finding_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_finding_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__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.get_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].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_finding_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -def test_list_findings(transport: str = 'grpc', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - ) - 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] == web_security_scanner.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' - - -def test_list_findings_from_dict(): - test_list_findings(request_type=dict) - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingsRequest() - - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - 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] == web_security_scanner.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - - -def test_list_findings_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.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 = web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.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', - filter='filter_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].filter == 'filter_value' - - -def test_list_findings_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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', - filter='filter_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].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_findings_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_findings_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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_finding_type_stats(transport: str = 'grpc', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse( - ) - response = client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -def test_list_finding_type_stats_from_dict(): - test_list_finding_type_stats(request_type=dict) - - -def test_list_finding_type_stats_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - client.list_finding_type_stats() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - response = await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async_from_dict(): - await test_list_finding_type_stats_async(request_type=dict) - - -def test_list_finding_type_stats_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_finding_type_stats_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_finding_type_stats_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_finding_type_stats( - 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_finding_type_stats_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_finding_type_stats( - 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_finding_type_stats_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_scan_config', - 'delete_scan_config', - 'get_scan_config', - 'list_scan_configs', - 'update_scan_config', - 'start_scan_run', - 'get_scan_run', - 'list_scan_runs', - 'stop_scan_run', - 'list_crawled_urls', - 'get_finding', - 'list_findings', - 'list_finding_type_stats', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - 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_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebSecurityScannerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebSecurityScannerClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebSecurityScannerGrpcTransport, grpc_helpers), - (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_web_security_scanner_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "websecurityscanner.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_web_security_scanner_host_no_port(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), - ) - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -def test_web_security_scanner_host_with_port(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), - ) - assert client.transport._host == 'websecurityscanner.googleapis.com:8000' - -def test_web_security_scanner_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_web_security_scanner_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_finding_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - finding = "octopus" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "project": "oyster", - "scan_config": "nudibranch", - "scan_run": "cuttlefish", - "finding": "mussel", - } - path = WebSecurityScannerClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_finding_path(path) - assert expected == actual - -def test_scan_config_path(): - project = "winkle" - scan_config = "nautilus" - expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - actual = WebSecurityScannerClient.scan_config_path(project, scan_config) - assert expected == actual - - -def test_parse_scan_config_path(): - expected = { - "project": "scallop", - "scan_config": "abalone", - } - path = WebSecurityScannerClient.scan_config_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_config_path(path) - assert expected == actual - -def test_scan_run_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) - assert expected == actual - - -def test_parse_scan_run_path(): - expected = { - "project": "octopus", - "scan_config": "oyster", - "scan_run": "nudibranch", - } - path = WebSecurityScannerClient.scan_run_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_run_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebSecurityScannerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = WebSecurityScannerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebSecurityScannerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = WebSecurityScannerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebSecurityScannerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = WebSecurityScannerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = WebSecurityScannerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = WebSecurityScannerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = WebSecurityScannerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = WebSecurityScannerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - transport_class = WebSecurityScannerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta/.coveragerc b/owl-bot-staging/v1beta/.coveragerc deleted file mode 100644 index 6b433c1..0000000 --- a/owl-bot-staging/v1beta/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/websecurityscanner/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta/MANIFEST.in b/owl-bot-staging/v1beta/MANIFEST.in deleted file mode 100644 index e23fd8a..0000000 --- a/owl-bot-staging/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/websecurityscanner *.py -recursive-include google/cloud/websecurityscanner_v1beta *.py diff --git a/owl-bot-staging/v1beta/README.rst b/owl-bot-staging/v1beta/README.rst deleted file mode 100644 index 4de4c10..0000000 --- a/owl-bot-staging/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Websecurityscanner API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Websecurityscanner API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta/docs/conf.py b/owl-bot-staging/v1beta/docs/conf.py deleted file mode 100644 index c393cbd..0000000 --- a/owl-bot-staging/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-websecurityscanner documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-websecurityscanner" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-websecurityscanner-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-websecurityscanner.tex", - u"google-cloud-websecurityscanner Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-websecurityscanner", - u"Google Cloud Websecurityscanner Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-websecurityscanner", - u"google-cloud-websecurityscanner Documentation", - author, - "google-cloud-websecurityscanner", - "GAPIC library for Google Cloud Websecurityscanner API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta/docs/index.rst b/owl-bot-staging/v1beta/docs/index.rst deleted file mode 100644 index c5a8dfe..0000000 --- a/owl-bot-staging/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - websecurityscanner_v1beta/services - websecurityscanner_v1beta/types diff --git a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst deleted file mode 100644 index 37adbdc..0000000 --- a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Websecurityscanner v1beta API -======================================================= -.. toctree:: - :maxdepth: 2 - - web_security_scanner diff --git a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst deleted file mode 100644 index 0a1ff8f..0000000 --- a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Websecurityscanner v1beta API -==================================================== - -.. automodule:: google.cloud.websecurityscanner_v1beta.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst b/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst deleted file mode 100644 index 8918ace..0000000 --- a/owl-bot-staging/v1beta/docs/websecurityscanner_v1beta/web_security_scanner.rst +++ /dev/null @@ -1,10 +0,0 @@ -WebSecurityScanner ------------------------------------- - -.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner - :members: - :inherited-members: - -.. automodule:: google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py deleted file mode 100644 index 0ea05a0..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.client import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.async_client import WebSecurityScannerAsyncClient - -from google.cloud.websecurityscanner_v1beta.types.crawled_url import CrawledUrl -from google.cloud.websecurityscanner_v1beta.types.finding import Finding -from google.cloud.websecurityscanner_v1beta.types.finding_addon import Form -from google.cloud.websecurityscanner_v1beta.types.finding_addon import OutdatedLibrary -from google.cloud.websecurityscanner_v1beta.types.finding_addon import ViolatingResource -from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableHeaders -from google.cloud.websecurityscanner_v1beta.types.finding_addon import VulnerableParameters -from google.cloud.websecurityscanner_v1beta.types.finding_addon import Xss -from google.cloud.websecurityscanner_v1beta.types.finding_type_stats import FindingTypeStats -from google.cloud.websecurityscanner_v1beta.types.scan_config import ScanConfig -from google.cloud.websecurityscanner_v1beta.types.scan_config_error import ScanConfigError -from google.cloud.websecurityscanner_v1beta.types.scan_run import ScanRun -from google.cloud.websecurityscanner_v1beta.types.scan_run_error_trace import ScanRunErrorTrace -from google.cloud.websecurityscanner_v1beta.types.scan_run_warning_trace import ScanRunWarningTrace -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import CreateScanConfigRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import DeleteScanConfigRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetFindingRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanConfigRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import GetScanRunRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListCrawledUrlsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListFindingTypeStatsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanConfigsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import ListScanRunsResponse -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StartScanRunRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import StopScanRunRequest -from google.cloud.websecurityscanner_v1beta.types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ('WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed b/owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed deleted file mode 100644 index 8cfb5d2..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.py deleted file mode 100644 index 130eb6c..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/__init__.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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.web_security_scanner import WebSecurityScannerClient -from .services.web_security_scanner import WebSecurityScannerAsyncClient - -from .types.crawled_url import CrawledUrl -from .types.finding import Finding -from .types.finding_addon import Form -from .types.finding_addon import OutdatedLibrary -from .types.finding_addon import ViolatingResource -from .types.finding_addon import VulnerableHeaders -from .types.finding_addon import VulnerableParameters -from .types.finding_addon import Xss -from .types.finding_type_stats import FindingTypeStats -from .types.scan_config import ScanConfig -from .types.scan_config_error import ScanConfigError -from .types.scan_run import ScanRun -from .types.scan_run_error_trace import ScanRunErrorTrace -from .types.scan_run_warning_trace import ScanRunWarningTrace -from .types.web_security_scanner import CreateScanConfigRequest -from .types.web_security_scanner import DeleteScanConfigRequest -from .types.web_security_scanner import GetFindingRequest -from .types.web_security_scanner import GetScanConfigRequest -from .types.web_security_scanner import GetScanRunRequest -from .types.web_security_scanner import ListCrawledUrlsRequest -from .types.web_security_scanner import ListCrawledUrlsResponse -from .types.web_security_scanner import ListFindingsRequest -from .types.web_security_scanner import ListFindingsResponse -from .types.web_security_scanner import ListFindingTypeStatsRequest -from .types.web_security_scanner import ListFindingTypeStatsResponse -from .types.web_security_scanner import ListScanConfigsRequest -from .types.web_security_scanner import ListScanConfigsResponse -from .types.web_security_scanner import ListScanRunsRequest -from .types.web_security_scanner import ListScanRunsResponse -from .types.web_security_scanner import StartScanRunRequest -from .types.web_security_scanner import StopScanRunRequest -from .types.web_security_scanner import UpdateScanConfigRequest - -__all__ = ( - 'WebSecurityScannerAsyncClient', -'CrawledUrl', -'CreateScanConfigRequest', -'DeleteScanConfigRequest', -'Finding', -'FindingTypeStats', -'Form', -'GetFindingRequest', -'GetScanConfigRequest', -'GetScanRunRequest', -'ListCrawledUrlsRequest', -'ListCrawledUrlsResponse', -'ListFindingTypeStatsRequest', -'ListFindingTypeStatsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListScanConfigsRequest', -'ListScanConfigsResponse', -'ListScanRunsRequest', -'ListScanRunsResponse', -'OutdatedLibrary', -'ScanConfig', -'ScanConfigError', -'ScanRun', -'ScanRunErrorTrace', -'ScanRunWarningTrace', -'StartScanRunRequest', -'StopScanRunRequest', -'UpdateScanConfigRequest', -'ViolatingResource', -'VulnerableHeaders', -'VulnerableParameters', -'WebSecurityScannerClient', -'Xss', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json deleted file mode 100644 index 114e6f0..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/gapic_metadata.json +++ /dev/null @@ -1,153 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.websecurityscanner_v1beta", - "protoPackage": "google.cloud.websecurityscanner.v1beta", - "schema": "1.0", - "services": { - "WebSecurityScanner": { - "clients": { - "grpc": { - "libraryClient": "WebSecurityScannerClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebSecurityScannerAsyncClient", - "rpcs": { - "CreateScanConfig": { - "methods": [ - "create_scan_config" - ] - }, - "DeleteScanConfig": { - "methods": [ - "delete_scan_config" - ] - }, - "GetFinding": { - "methods": [ - "get_finding" - ] - }, - "GetScanConfig": { - "methods": [ - "get_scan_config" - ] - }, - "GetScanRun": { - "methods": [ - "get_scan_run" - ] - }, - "ListCrawledUrls": { - "methods": [ - "list_crawled_urls" - ] - }, - "ListFindingTypeStats": { - "methods": [ - "list_finding_type_stats" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListScanConfigs": { - "methods": [ - "list_scan_configs" - ] - }, - "ListScanRuns": { - "methods": [ - "list_scan_runs" - ] - }, - "StartScanRun": { - "methods": [ - "start_scan_run" - ] - }, - "StopScanRun": { - "methods": [ - "stop_scan_run" - ] - }, - "UpdateScanConfig": { - "methods": [ - "update_scan_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed deleted file mode 100644 index 8cfb5d2..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-websecurityscanner package uses inline types. diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py deleted file mode 100644 index 46b053b..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import WebSecurityScannerClient -from .async_client import WebSecurityScannerAsyncClient - -__all__ = ( - 'WebSecurityScannerClient', - 'WebSecurityScannerAsyncClient', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py deleted file mode 100644 index 8942159..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/async_client.py +++ /dev/null @@ -1,1316 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_addon -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport -from .client import WebSecurityScannerClient - - -class WebSecurityScannerAsyncClient: - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - _client: WebSecurityScannerClient - - DEFAULT_ENDPOINT = WebSecurityScannerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebSecurityScannerClient.DEFAULT_MTLS_ENDPOINT - - finding_path = staticmethod(WebSecurityScannerClient.finding_path) - parse_finding_path = staticmethod(WebSecurityScannerClient.parse_finding_path) - scan_config_path = staticmethod(WebSecurityScannerClient.scan_config_path) - parse_scan_config_path = staticmethod(WebSecurityScannerClient.parse_scan_config_path) - scan_run_path = staticmethod(WebSecurityScannerClient.scan_run_path) - parse_scan_run_path = staticmethod(WebSecurityScannerClient.parse_scan_run_path) - common_billing_account_path = staticmethod(WebSecurityScannerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebSecurityScannerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebSecurityScannerClient.common_folder_path) - parse_common_folder_path = staticmethod(WebSecurityScannerClient.parse_common_folder_path) - common_organization_path = staticmethod(WebSecurityScannerClient.common_organization_path) - parse_common_organization_path = staticmethod(WebSecurityScannerClient.parse_common_organization_path) - common_project_path = staticmethod(WebSecurityScannerClient.common_project_path) - parse_common_project_path = staticmethod(WebSecurityScannerClient.parse_common_project_path) - common_location_path = staticmethod(WebSecurityScannerClient.common_location_path) - parse_common_location_path = staticmethod(WebSecurityScannerClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_info.__func__(WebSecurityScannerAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerAsyncClient: The constructed client. - """ - return WebSecurityScannerClient.from_service_account_file.__func__(WebSecurityScannerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WebSecurityScannerClient).get_transport_class, type(WebSecurityScannerClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, WebSecurityScannerTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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, ~.WebSecurityScannerTransport]): 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 = WebSecurityScannerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_scan_config(self, - request: web_security_scanner.CreateScanConfigRequest = None, - *, - parent: str = None, - scan_config: gcw_scan_config.ScanConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest`): - The request object. Request for the `CreateScanConfig` - method. - parent (:class:`str`): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, scan_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.CreateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_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_scan_config, - default_timeout=600.0, - client_info=DEFAULT_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_scan_config(self, - request: web_security_scanner.DeleteScanConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest`): - The request object. Request for the `DeleteScanConfig` - method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.DeleteScanConfigRequest(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_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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_scan_config(self, - request: web_security_scanner.GetScanConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest`): - The request object. Request for the `GetScanConfig` - method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.GetScanConfigRequest(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_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_scan_configs(self, - request: web_security_scanner.ListScanConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsAsyncPager: - r"""Lists ScanConfigs under a given project. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest`): - The request object. Request for the `ListScanConfigs` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsAsyncPager: - Response for the ListScanConfigs method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListScanConfigsRequest(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_scan_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListScanConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_scan_config(self, - request: web_security_scanner.UpdateScanConfigRequest = None, - *, - scan_config: gcw_scan_config.ScanConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest`): - The request object. Request for the - `UpdateScanConfigRequest` method. - scan_config (:class:`google.cloud.websecurityscanner_v1beta.types.ScanConfig`): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.UpdateScanConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_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_scan_config, - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def start_scan_run(self, - request: web_security_scanner.StartScanRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest`): - The request object. Request for the `StartScanRun` - method. - name (:class:`str`): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.StartScanRunRequest(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.start_scan_run, - default_timeout=600.0, - client_info=DEFAULT_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_scan_run(self, - request: web_security_scanner.GetScanRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest`): - The request object. Request for the `GetScanRun` method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.GetScanRunRequest(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_scan_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_scan_runs(self, - request: web_security_scanner.ListScanRunsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsAsyncPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest`): - The request object. Request for the `ListScanRuns` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsAsyncPager: - Response for the ListScanRuns method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListScanRunsRequest(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_scan_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListScanRunsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def stop_scan_run(self, - request: web_security_scanner.StopScanRunRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest`): - The request object. Request for the `StopScanRun` - method. - name (:class:`str`): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.StopScanRunRequest(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.stop_scan_run, - default_timeout=600.0, - client_info=DEFAULT_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 list_crawled_urls(self, - request: web_security_scanner.ListCrawledUrlsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsAsyncPager: - r"""List CrawledUrls under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest`): - The request object. Request for the `ListCrawledUrls` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsAsyncPager: - Response for the ListCrawledUrls method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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.ListCrawledUrlsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_finding(self, - request: web_security_scanner.GetFindingRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.GetFindingRequest`): - The request object. Request for the `GetFinding` method. - name (:class:`str`): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.GetFindingRequest(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_finding, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 list_findings(self, - request: web_security_scanner.ListFindingsRequest = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""List Findings under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest`): - The request object. Request for the `ListFindings` - method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsAsyncPager: - Response for the ListFindings method. - - 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, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_findings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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_finding_type_stats(self, - request: web_security_scanner.ListFindingTypeStatsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - Args: - request (:class:`google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest`): - The request object. Request for the - `ListFindingTypeStats` method. - parent (:class:`str`): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats 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([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-websecurityscanner", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebSecurityScannerAsyncClient", -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py deleted file mode 100644 index 6beadac..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py +++ /dev/null @@ -1,1462 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_addon -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebSecurityScannerGrpcTransport -from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport - - -class WebSecurityScannerClientMeta(type): - """Metaclass for the WebSecurityScanner 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[WebSecurityScannerTransport]] - _transport_registry["grpc"] = WebSecurityScannerGrpcTransport - _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[WebSecurityScannerTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class WebSecurityScannerClient(metaclass=WebSecurityScannerClientMeta): - """Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "websecurityscanner.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - WebSecurityScannerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebSecurityScannerTransport: - """Returns the transport used by the client instance. - - Returns: - WebSecurityScannerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def finding_path(project: str,scan_config: str,scan_run: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_config_path(project: str,scan_config: str,) -> str: - """Returns a fully-qualified scan_config string.""" - return "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - - @staticmethod - def parse_scan_config_path(path: str) -> Dict[str,str]: - """Parses a scan_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def scan_run_path(project: str,scan_config: str,scan_run: str,) -> str: - """Returns a fully-qualified scan_run string.""" - return "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - - @staticmethod - def parse_scan_run_path(path: str) -> Dict[str,str]: - """Parses a scan_run path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/scanConfigs/(?P.+?)/scanRuns/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, WebSecurityScannerTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the web security scanner 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, WebSecurityScannerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, WebSecurityScannerTransport): - # transport is a WebSecurityScannerTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_scan_config(self, - request: Union[web_security_scanner.CreateScanConfigRequest, dict] = None, - *, - parent: str = None, - scan_config: gcw_scan_config.ScanConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Creates a new ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.CreateScanConfigRequest, dict]): - The request object. Request for the `CreateScanConfig` - method. - parent (str): - Required. The parent resource name - where the scan is created, which should - be a project resource name in the format - 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be - created. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, scan_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 web_security_scanner.CreateScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.CreateScanConfigRequest): - request = web_security_scanner.CreateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if scan_config is not None: - request.scan_config = scan_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_scan_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_scan_config(self, - request: Union[web_security_scanner.DeleteScanConfigRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing ScanConfig and its child - resources. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.DeleteScanConfigRequest, dict]): - The request object. Request for the `DeleteScanConfig` - method. - name (str): - Required. The resource name of the - ScanConfig to be deleted. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - 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 web_security_scanner.DeleteScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.DeleteScanConfigRequest): - request = web_security_scanner.DeleteScanConfigRequest(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_scan_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_scan_config(self, - request: Union[web_security_scanner.GetScanConfigRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_config.ScanConfig: - r"""Gets a ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanConfigRequest, dict]): - The request object. Request for the `GetScanConfig` - method. - name (str): - Required. The resource name of the - ScanConfig to be returned. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.GetScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetScanConfigRequest): - request = web_security_scanner.GetScanConfigRequest(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_scan_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 list_scan_configs(self, - request: Union[web_security_scanner.ListScanConfigsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanConfigsPager: - r"""Lists ScanConfigs under a given project. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest, dict]): - The request object. Request for the `ListScanConfigs` - method. - parent (str): - Required. The parent resource name, - which should be a project resource name - in the format 'projects/{projectId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanConfigsPager: - Response for the ListScanConfigs method. - - 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 web_security_scanner.ListScanConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListScanConfigsRequest): - request = web_security_scanner.ListScanConfigsRequest(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_scan_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.ListScanConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_scan_config(self, - request: Union[web_security_scanner.UpdateScanConfigRequest, dict] = None, - *, - scan_config: gcw_scan_config.ScanConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcw_scan_config.ScanConfig: - r"""Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.UpdateScanConfigRequest, dict]): - The request object. Request for the - `UpdateScanConfigRequest` method. - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be - updated. The name field must be set to - identify the resource to be updated. The - values of fields not covered by the mask - will be ignored. - - This corresponds to the ``scan_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For - the ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanConfig: - A ScanConfig resource contains the - configurations to launch a scan. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([scan_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 web_security_scanner.UpdateScanConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.UpdateScanConfigRequest): - request = web_security_scanner.UpdateScanConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scan_config is not None: - request.scan_config = scan_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_scan_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scan_config.name", request.scan_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def start_scan_run(self, - request: Union[web_security_scanner.StartScanRunRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Start a ScanRun according to the given ScanConfig. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.StartScanRunRequest, dict]): - The request object. Request for the `StartScanRun` - method. - name (str): - Required. The resource name of the - ScanConfig to be used. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.StartScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.StartScanRunRequest): - request = web_security_scanner.StartScanRunRequest(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.start_scan_run] - - # 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_scan_run(self, - request: Union[web_security_scanner.GetScanRunRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Gets a ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.GetScanRunRequest, dict]): - The request object. Request for the `GetScanRun` method. - name (str): - Required. The resource name of the - ScanRun to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.GetScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetScanRunRequest): - request = web_security_scanner.GetScanRunRequest(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_scan_run] - - # 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 list_scan_runs(self, - request: Union[web_security_scanner.ListScanRunsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListScanRunsPager: - r"""Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest, dict]): - The request object. Request for the `ListScanRuns` - method. - parent (str): - Required. The parent resource name, - which should be a scan resource name in - the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListScanRunsPager: - Response for the ListScanRuns method. - - 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 web_security_scanner.ListScanRunsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListScanRunsRequest): - request = web_security_scanner.ListScanRunsRequest(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_scan_runs] - - # 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.ListScanRunsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def stop_scan_run(self, - request: Union[web_security_scanner.StopScanRunRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> scan_run.ScanRun: - r"""Stops a ScanRun. The stopped ScanRun is returned. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.StopScanRunRequest, dict]): - The request object. Request for the `StopScanRun` - method. - name (str): - Required. The resource name of the - ScanRun to be stopped. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ScanRun: - A ScanRun is a output-only resource - representing an actual run of the scan. - Next id: 12 - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.StopScanRunRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.StopScanRunRequest): - request = web_security_scanner.StopScanRunRequest(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.stop_scan_run] - - # 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 list_crawled_urls(self, - request: Union[web_security_scanner.ListCrawledUrlsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCrawledUrlsPager: - r"""List CrawledUrls under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest, dict]): - The request object. Request for the `ListCrawledUrls` - method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListCrawledUrlsPager: - Response for the ListCrawledUrls method. - - 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 web_security_scanner.ListCrawledUrlsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListCrawledUrlsRequest): - request = web_security_scanner.ListCrawledUrlsRequest(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_crawled_urls] - - # 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.ListCrawledUrlsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_finding(self, - request: Union[web_security_scanner.GetFindingRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Gets a Finding. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.GetFindingRequest, dict]): - The request object. Request for the `GetFinding` method. - name (str): - Required. The resource name of the - Finding to be returned. The name follows - the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.Finding: - A Finding resource represents a - vulnerability instance identified during - a ScanRun. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 web_security_scanner.GetFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.GetFindingRequest): - request = web_security_scanner.GetFindingRequest(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_finding] - - # 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 list_findings(self, - request: Union[web_security_scanner.ListFindingsRequest, dict] = None, - *, - parent: str = None, - filter: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""List Findings under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest, dict]): - The request object. Request for the `ListFindings` - method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Required. The filter expression. The expression must be - in the format: . Supported field: 'finding_type'. - Supported operator: '='. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.services.web_security_scanner.pagers.ListFindingsPager: - Response for the ListFindings method. - - 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, filter]) - if request is 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 web_security_scanner.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListFindingsRequest): - request = web_security_scanner.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # 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_finding_type_stats(self, - request: Union[web_security_scanner.ListFindingTypeStatsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> web_security_scanner.ListFindingTypeStatsResponse: - r"""List all FindingTypeStats under a given ScanRun. - - Args: - request (Union[google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsRequest, dict]): - The request object. Request for the - `ListFindingTypeStats` method. - parent (str): - Required. The parent resource name, - which should be a scan run resource name - in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.websecurityscanner_v1beta.types.ListFindingTypeStatsResponse: - Response for the ListFindingTypeStats 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([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 web_security_scanner.ListFindingTypeStatsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, web_security_scanner.ListFindingTypeStatsRequest): - request = web_security_scanner.ListFindingTypeStatsRequest(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_finding_type_stats] - - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-websecurityscanner", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebSecurityScannerClient", -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py deleted file mode 100644 index 61ca2bf..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/pagers.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner - - -class ListScanConfigsPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` - 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[..., web_security_scanner.ListScanConfigsResponse], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): - 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 = web_security_scanner.ListScanConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - for page in self.pages: - yield from page.scan_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanConfigsAsyncPager: - """A pager for iterating through ``list_scan_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanConfigs`` requests and continue to iterate - through the ``scan_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse` - 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[web_security_scanner.ListScanConfigsResponse]], - request: web_security_scanner.ListScanConfigsRequest, - response: web_security_scanner.ListScanConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanConfigsResponse): - 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 = web_security_scanner.ListScanConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListScanConfigsResponse]: - 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[scan_config.ScanConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` - 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[..., web_security_scanner.ListScanRunsResponse], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): - 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 = web_security_scanner.ListScanRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - for page in self.pages: - yield from page.scan_runs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListScanRunsAsyncPager: - """A pager for iterating through ``list_scan_runs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``scan_runs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListScanRuns`` requests and continue to iterate - through the ``scan_runs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse` - 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[web_security_scanner.ListScanRunsResponse]], - request: web_security_scanner.ListScanRunsRequest, - response: web_security_scanner.ListScanRunsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListScanRunsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListScanRunsResponse): - 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 = web_security_scanner.ListScanRunsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListScanRunsResponse]: - 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[scan_run.ScanRun]: - async def async_generator(): - async for page in self.pages: - for response in page.scan_runs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` - 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[..., web_security_scanner.ListCrawledUrlsResponse], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): - 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 = web_security_scanner.ListCrawledUrlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - for page in self.pages: - yield from page.crawled_urls - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCrawledUrlsAsyncPager: - """A pager for iterating through ``list_crawled_urls`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crawled_urls`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCrawledUrls`` requests and continue to iterate - through the ``crawled_urls`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse` - 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[web_security_scanner.ListCrawledUrlsResponse]], - request: web_security_scanner.ListCrawledUrlsRequest, - response: web_security_scanner.ListCrawledUrlsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListCrawledUrlsResponse): - 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 = web_security_scanner.ListCrawledUrlsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[web_security_scanner.ListCrawledUrlsResponse]: - 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[crawled_url.CrawledUrl]: - async def async_generator(): - async for page in self.pages: - for response in page.crawled_urls: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., web_security_scanner.ListFindingsResponse], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[web_security_scanner.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[web_security_scanner.ListFindingsResponse]], - request: web_security_scanner.ListFindingsRequest, - response: web_security_scanner.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.websecurityscanner_v1beta.types.ListFindingsRequest): - The initial request object. - response (google.cloud.websecurityscanner_v1beta.types.ListFindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = web_security_scanner.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[web_security_scanner.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) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py deleted file mode 100644 index 19f4df5..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import WebSecurityScannerTransport -from .grpc import WebSecurityScannerGrpcTransport -from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebSecurityScannerTransport]] -_transport_registry['grpc'] = WebSecurityScannerGrpcTransport -_transport_registry['grpc_asyncio'] = WebSecurityScannerGrpcAsyncIOTransport - -__all__ = ( - 'WebSecurityScannerTransport', - 'WebSecurityScannerGrpcTransport', - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py deleted file mode 100644 index b9d0a1c..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/base.py +++ /dev/null @@ -1,404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-websecurityscanner', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class WebSecurityScannerTransport(abc.ABC): - """Abstract transport class for WebSecurityScanner.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'websecurityscanner.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_scan_config: gapic_v1.method.wrap_method( - self.create_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.delete_scan_config: gapic_v1.method.wrap_method( - self.delete_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_config: gapic_v1.method.wrap_method( - self.get_scan_config, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_configs: gapic_v1.method.wrap_method( - self.list_scan_configs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.update_scan_config: gapic_v1.method.wrap_method( - self.update_scan_config, - default_timeout=600.0, - client_info=client_info, - ), - self.start_scan_run: gapic_v1.method.wrap_method( - self.start_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.get_scan_run: gapic_v1.method.wrap_method( - self.get_scan_run, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_scan_runs: gapic_v1.method.wrap_method( - self.list_scan_runs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.stop_scan_run: gapic_v1.method.wrap_method( - self.stop_scan_run, - default_timeout=600.0, - client_info=client_info, - ), - self.list_crawled_urls: gapic_v1.method.wrap_method( - self.list_crawled_urls, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_finding: gapic_v1.method.wrap_method( - self.get_finding, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.list_finding_type_stats: gapic_v1.method.wrap_method( - self.list_finding_type_stats, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Union[ - scan_config.ScanConfig, - Awaitable[scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Union[ - web_security_scanner.ListScanConfigsResponse, - Awaitable[web_security_scanner.ListScanConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Union[ - gcw_scan_config.ScanConfig, - Awaitable[gcw_scan_config.ScanConfig] - ]]: - raise NotImplementedError() - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Union[ - web_security_scanner.ListScanRunsResponse, - Awaitable[web_security_scanner.ListScanRunsResponse] - ]]: - raise NotImplementedError() - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Union[ - scan_run.ScanRun, - Awaitable[scan_run.ScanRun] - ]]: - raise NotImplementedError() - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Union[ - web_security_scanner.ListCrawledUrlsResponse, - Awaitable[web_security_scanner.ListCrawledUrlsResponse] - ]]: - raise NotImplementedError() - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Union[ - web_security_scanner.ListFindingsResponse, - Awaitable[web_security_scanner.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Union[ - web_security_scanner.ListFindingTypeStatsResponse, - Awaitable[web_security_scanner.ListFindingTypeStatsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'WebSecurityScannerTransport', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py deleted file mode 100644 index b2bb084..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc.py +++ /dev/null @@ -1,575 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO - - -class WebSecurityScannerGrpcTransport(WebSecurityScannerTransport): - """gRPC backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - 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 = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - ~.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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - scan_config.ScanConfig]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - web_security_scanner.ListScanConfigsResponse]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - ~.ListScanConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - gcw_scan_config.ScanConfig]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - ~.ScanConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - web_security_scanner.ListScanRunsResponse]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - ~.ListScanRunsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - scan_run.ScanRun]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - ~.ScanRun]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - web_security_scanner.ListCrawledUrlsResponse]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - ~.ListCrawledUrlsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - finding.Finding]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - ~.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 'get_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - web_security_scanner.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - 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.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - web_security_scanner.ListFindingTypeStatsResponse]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - ~.ListFindingTypeStatsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - -__all__ = ( - 'WebSecurityScannerGrpcTransport', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py deleted file mode 100644 index d9d49d3..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/grpc_asyncio.py +++ /dev/null @@ -1,579 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.protobuf import empty_pb2 # type: ignore -from .base import WebSecurityScannerTransport, DEFAULT_CLIENT_INFO -from .grpc import WebSecurityScannerGrpcTransport - - -class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): - """gRPC AsyncIO backend transport for WebSecurityScanner. - - Cloud Web Security Scanner Service identifies security - vulnerabilities in web applications hosted on Google Cloud - Platform. It crawls your application, and attempts to exercise - as many user inputs and event handlers as possible. - - 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 = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'websecurityscanner.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_scan_config(self) -> Callable[ - [web_security_scanner.CreateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the create scan config method over gRPC. - - Creates a new ScanConfig. - - Returns: - Callable[[~.CreateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['create_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/CreateScanConfig', - request_serializer=web_security_scanner.CreateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['create_scan_config'] - - @property - def delete_scan_config(self) -> Callable[ - [web_security_scanner.DeleteScanConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete scan config method over gRPC. - - Deletes an existing ScanConfig and its child - resources. - - Returns: - Callable[[~.DeleteScanConfigRequest], - 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_scan_config' not in self._stubs: - self._stubs['delete_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/DeleteScanConfig', - request_serializer=web_security_scanner.DeleteScanConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_scan_config'] - - @property - def get_scan_config(self) -> Callable[ - [web_security_scanner.GetScanConfigRequest], - Awaitable[scan_config.ScanConfig]]: - r"""Return a callable for the get scan config method over gRPC. - - Gets a ScanConfig. - - Returns: - Callable[[~.GetScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['get_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanConfig', - request_serializer=web_security_scanner.GetScanConfigRequest.serialize, - response_deserializer=scan_config.ScanConfig.deserialize, - ) - return self._stubs['get_scan_config'] - - @property - def list_scan_configs(self) -> Callable[ - [web_security_scanner.ListScanConfigsRequest], - Awaitable[web_security_scanner.ListScanConfigsResponse]]: - r"""Return a callable for the list scan configs method over gRPC. - - Lists ScanConfigs under a given project. - - Returns: - Callable[[~.ListScanConfigsRequest], - Awaitable[~.ListScanConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_configs' not in self._stubs: - self._stubs['list_scan_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanConfigs', - request_serializer=web_security_scanner.ListScanConfigsRequest.serialize, - response_deserializer=web_security_scanner.ListScanConfigsResponse.deserialize, - ) - return self._stubs['list_scan_configs'] - - @property - def update_scan_config(self) -> Callable[ - [web_security_scanner.UpdateScanConfigRequest], - Awaitable[gcw_scan_config.ScanConfig]]: - r"""Return a callable for the update scan config method over gRPC. - - Updates a ScanConfig. This method support partial - update of a ScanConfig. - - Returns: - Callable[[~.UpdateScanConfigRequest], - Awaitable[~.ScanConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_config' not in self._stubs: - self._stubs['update_scan_config'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/UpdateScanConfig', - request_serializer=web_security_scanner.UpdateScanConfigRequest.serialize, - response_deserializer=gcw_scan_config.ScanConfig.deserialize, - ) - return self._stubs['update_scan_config'] - - @property - def start_scan_run(self) -> Callable[ - [web_security_scanner.StartScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the start scan run method over gRPC. - - Start a ScanRun according to the given ScanConfig. - - Returns: - Callable[[~.StartScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_scan_run' not in self._stubs: - self._stubs['start_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StartScanRun', - request_serializer=web_security_scanner.StartScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['start_scan_run'] - - @property - def get_scan_run(self) -> Callable[ - [web_security_scanner.GetScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the get scan run method over gRPC. - - Gets a ScanRun. - - Returns: - Callable[[~.GetScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_run' not in self._stubs: - self._stubs['get_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetScanRun', - request_serializer=web_security_scanner.GetScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['get_scan_run'] - - @property - def list_scan_runs(self) -> Callable[ - [web_security_scanner.ListScanRunsRequest], - Awaitable[web_security_scanner.ListScanRunsResponse]]: - r"""Return a callable for the list scan runs method over gRPC. - - Lists ScanRuns under a given ScanConfig, in - descending order of ScanRun stop time. - - Returns: - Callable[[~.ListScanRunsRequest], - Awaitable[~.ListScanRunsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_scan_runs' not in self._stubs: - self._stubs['list_scan_runs'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListScanRuns', - request_serializer=web_security_scanner.ListScanRunsRequest.serialize, - response_deserializer=web_security_scanner.ListScanRunsResponse.deserialize, - ) - return self._stubs['list_scan_runs'] - - @property - def stop_scan_run(self) -> Callable[ - [web_security_scanner.StopScanRunRequest], - Awaitable[scan_run.ScanRun]]: - r"""Return a callable for the stop scan run method over gRPC. - - Stops a ScanRun. The stopped ScanRun is returned. - - Returns: - Callable[[~.StopScanRunRequest], - Awaitable[~.ScanRun]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_scan_run' not in self._stubs: - self._stubs['stop_scan_run'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/StopScanRun', - request_serializer=web_security_scanner.StopScanRunRequest.serialize, - response_deserializer=scan_run.ScanRun.deserialize, - ) - return self._stubs['stop_scan_run'] - - @property - def list_crawled_urls(self) -> Callable[ - [web_security_scanner.ListCrawledUrlsRequest], - Awaitable[web_security_scanner.ListCrawledUrlsResponse]]: - r"""Return a callable for the list crawled urls method over gRPC. - - List CrawledUrls under a given ScanRun. - - Returns: - Callable[[~.ListCrawledUrlsRequest], - Awaitable[~.ListCrawledUrlsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crawled_urls' not in self._stubs: - self._stubs['list_crawled_urls'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListCrawledUrls', - request_serializer=web_security_scanner.ListCrawledUrlsRequest.serialize, - response_deserializer=web_security_scanner.ListCrawledUrlsResponse.deserialize, - ) - return self._stubs['list_crawled_urls'] - - @property - def get_finding(self) -> Callable[ - [web_security_scanner.GetFindingRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the get finding method over gRPC. - - Gets a Finding. - - Returns: - Callable[[~.GetFindingRequest], - 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 'get_finding' not in self._stubs: - self._stubs['get_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/GetFinding', - request_serializer=web_security_scanner.GetFindingRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['get_finding'] - - @property - def list_findings(self) -> Callable[ - [web_security_scanner.ListFindingsRequest], - Awaitable[web_security_scanner.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - List Findings under a given ScanRun. - - 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.websecurityscanner.v1beta.WebSecurityScanner/ListFindings', - request_serializer=web_security_scanner.ListFindingsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_finding_type_stats(self) -> Callable[ - [web_security_scanner.ListFindingTypeStatsRequest], - Awaitable[web_security_scanner.ListFindingTypeStatsResponse]]: - r"""Return a callable for the list finding type stats method over gRPC. - - List all FindingTypeStats under a given ScanRun. - - Returns: - Callable[[~.ListFindingTypeStatsRequest], - Awaitable[~.ListFindingTypeStatsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_type_stats' not in self._stubs: - self._stubs['list_finding_type_stats'] = self.grpc_channel.unary_unary( - '/google.cloud.websecurityscanner.v1beta.WebSecurityScanner/ListFindingTypeStats', - request_serializer=web_security_scanner.ListFindingTypeStatsRequest.serialize, - response_deserializer=web_security_scanner.ListFindingTypeStatsResponse.deserialize, - ) - return self._stubs['list_finding_type_stats'] - - -__all__ = ( - 'WebSecurityScannerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py deleted file mode 100644 index 36cb2b7..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/__init__.py +++ /dev/null @@ -1,102 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .crawled_url import ( - CrawledUrl, -) -from .finding import ( - Finding, -) -from .finding_addon import ( - Form, - OutdatedLibrary, - ViolatingResource, - VulnerableHeaders, - VulnerableParameters, - Xss, -) -from .finding_type_stats import ( - FindingTypeStats, -) -from .scan_config import ( - ScanConfig, -) -from .scan_config_error import ( - ScanConfigError, -) -from .scan_run import ( - ScanRun, -) -from .scan_run_error_trace import ( - ScanRunErrorTrace, -) -from .scan_run_warning_trace import ( - ScanRunWarningTrace, -) -from .web_security_scanner import ( - CreateScanConfigRequest, - DeleteScanConfigRequest, - GetFindingRequest, - GetScanConfigRequest, - GetScanRunRequest, - ListCrawledUrlsRequest, - ListCrawledUrlsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListFindingTypeStatsRequest, - ListFindingTypeStatsResponse, - ListScanConfigsRequest, - ListScanConfigsResponse, - ListScanRunsRequest, - ListScanRunsResponse, - StartScanRunRequest, - StopScanRunRequest, - UpdateScanConfigRequest, -) - -__all__ = ( - 'CrawledUrl', - 'Finding', - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableHeaders', - 'VulnerableParameters', - 'Xss', - 'FindingTypeStats', - 'ScanConfig', - 'ScanConfigError', - 'ScanRun', - 'ScanRunErrorTrace', - 'ScanRunWarningTrace', - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetFindingRequest', - 'GetScanConfigRequest', - 'GetScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - 'ListScanConfigsRequest', - 'ListScanConfigsResponse', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StartScanRunRequest', - 'StopScanRunRequest', - 'UpdateScanConfigRequest', -) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py deleted file mode 100644 index 217dcf9..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/crawled_url.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'CrawledUrl', - }, -) - - -class CrawledUrl(proto.Message): - r"""A CrawledUrl resource represents a URL that was crawled - during a ScanRun. Web Security Scanner Service crawls the web - applications, following all links within the scope of sites, to - find the URLs to test against. - - Attributes: - http_method (str): - The http method of the request that was used - to visit the URL, in uppercase. - url (str): - The URL that was crawled. - body (str): - The body of the request that was used to - visit the URL. - """ - - http_method = proto.Field( - proto.STRING, - number=1, - ) - url = proto.Field( - proto.STRING, - number=2, - ) - body = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py deleted file mode 100644 index 273aa54..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding.py +++ /dev/null @@ -1,165 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import finding_addon - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""A Finding resource represents a vulnerability instance - identified during a ScanRun. - - Attributes: - name (str): - The resource name of the Finding. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanruns/{scanRunId}/findings/{findingId}'. - The finding IDs are generated by the system. - finding_type (str): - The type of the Finding. - Detailed and up-to-date information on findings - can be found here: - https://cloud.google.com/security- - scanner/docs/scan-result-details - http_method (str): - The http method of the request that triggered - the vulnerability, in uppercase. - fuzzed_url (str): - The URL produced by the server-side fuzzer - and used in the request that triggered the - vulnerability. - body (str): - The body of the request that triggered the - vulnerability. - description (str): - The description of the vulnerability. - reproduction_url (str): - The URL containing human-readable payload - that user can leverage to reproduce the - vulnerability. - frame_url (str): - If the vulnerability was originated from - nested IFrame, the immediate parent IFrame is - reported. - final_url (str): - The URL where the browser lands when the - vulnerability is detected. - tracking_id (str): - The tracking ID uniquely identifies a - vulnerability instance across multiple ScanRuns. - form (google.cloud.websecurityscanner_v1beta.types.Form): - An addon containing information reported for - a vulnerability with an HTML form, if any. - outdated_library (google.cloud.websecurityscanner_v1beta.types.OutdatedLibrary): - An addon containing information about - outdated libraries. - violating_resource (google.cloud.websecurityscanner_v1beta.types.ViolatingResource): - An addon containing detailed information - regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, - etc. - vulnerable_headers (google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders): - An addon containing information about - vulnerable or missing HTTP headers. - vulnerable_parameters (google.cloud.websecurityscanner_v1beta.types.VulnerableParameters): - An addon containing information about request - parameters which were found to be vulnerable. - xss (google.cloud.websecurityscanner_v1beta.types.Xss): - An addon containing information reported for - an XSS, if any. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - finding_type = proto.Field( - proto.STRING, - number=2, - ) - http_method = proto.Field( - proto.STRING, - number=3, - ) - fuzzed_url = proto.Field( - proto.STRING, - number=4, - ) - body = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - reproduction_url = proto.Field( - proto.STRING, - number=7, - ) - frame_url = proto.Field( - proto.STRING, - number=8, - ) - final_url = proto.Field( - proto.STRING, - number=9, - ) - tracking_id = proto.Field( - proto.STRING, - number=10, - ) - form = proto.Field( - proto.MESSAGE, - number=16, - message=finding_addon.Form, - ) - outdated_library = proto.Field( - proto.MESSAGE, - number=11, - message=finding_addon.OutdatedLibrary, - ) - violating_resource = proto.Field( - proto.MESSAGE, - number=12, - message=finding_addon.ViolatingResource, - ) - vulnerable_headers = proto.Field( - proto.MESSAGE, - number=15, - message=finding_addon.VulnerableHeaders, - ) - vulnerable_parameters = proto.Field( - proto.MESSAGE, - number=13, - message=finding_addon.VulnerableParameters, - ) - xss = proto.Field( - proto.MESSAGE, - number=14, - message=finding_addon.Xss, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py deleted file mode 100644 index 98f3b7a..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_addon.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'Form', - 'OutdatedLibrary', - 'ViolatingResource', - 'VulnerableParameters', - 'VulnerableHeaders', - 'Xss', - }, -) - - -class Form(proto.Message): - r"""! Information about a vulnerability with an HTML. - Attributes: - action_uri (str): - ! The URI where to send the form when it's - submitted. - fields (Sequence[str]): - ! The names of form fields related to the - vulnerability. - """ - - action_uri = proto.Field( - proto.STRING, - number=1, - ) - fields = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class OutdatedLibrary(proto.Message): - r"""Information reported for an outdated library. - Attributes: - library_name (str): - The name of the outdated library. - version (str): - The version number. - learn_more_urls (Sequence[str]): - URLs to learn more information about the - vulnerabilities in the library. - """ - - library_name = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - learn_more_urls = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ViolatingResource(proto.Message): - r"""Information regarding any resource causing the vulnerability - such as JavaScript sources, image, audio files, etc. - - Attributes: - content_type (str): - The MIME type of this resource. - resource_url (str): - URL of this violating resource. - """ - - content_type = proto.Field( - proto.STRING, - number=1, - ) - resource_url = proto.Field( - proto.STRING, - number=2, - ) - - -class VulnerableParameters(proto.Message): - r"""Information about vulnerable request parameters. - Attributes: - parameter_names (Sequence[str]): - The vulnerable parameter names. - """ - - parameter_names = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VulnerableHeaders(proto.Message): - r"""Information about vulnerable or missing HTTP Headers. - Attributes: - headers (Sequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): - List of vulnerable headers. - missing_headers (Sequence[google.cloud.websecurityscanner_v1beta.types.VulnerableHeaders.Header]): - List of missing headers. - """ - - class Header(proto.Message): - r"""Describes a HTTP Header. - Attributes: - name (str): - Header name. - value (str): - Header value. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.STRING, - number=2, - ) - - headers = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Header, - ) - missing_headers = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Header, - ) - - -class Xss(proto.Message): - r"""Information reported for an XSS. - Attributes: - stack_traces (Sequence[str]): - Stack traces leading to the point where the - XSS occurred. - error_message (str): - An error message generated by a javascript - breakage. - """ - - stack_traces = proto.RepeatedField( - proto.STRING, - number=1, - ) - error_message = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py deleted file mode 100644 index 35d888f..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/finding_type_stats.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'FindingTypeStats', - }, -) - - -class FindingTypeStats(proto.Message): - r"""A FindingTypeStats resource represents stats regarding a - specific FindingType of Findings under a given ScanRun. - - Attributes: - finding_type (str): - The finding type associated with the stats. - finding_count (int): - The count of findings belonging to this - finding type. - """ - - finding_type = proto.Field( - proto.STRING, - number=1, - ) - finding_count = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py deleted file mode 100644 index 1b033dc..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanConfig', - }, -) - - -class ScanConfig(proto.Message): - r"""A ScanConfig resource contains the configurations to launch a - scan. - - Attributes: - name (str): - The resource name of the ScanConfig. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - The ScanConfig IDs are generated by the system. - display_name (str): - Required. The user provided display name of - the ScanConfig. - max_qps (int): - The maximum QPS during scanning. A valid value ranges from 5 - to 20 inclusively. If the field is unspecified or its value - is set 0, server will default to 15. Other values outside of - [5, 20] range will be rejected with INVALID_ARGUMENT error. - starting_urls (Sequence[str]): - Required. The starting URLs from which the - scanner finds site pages. - authentication (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication): - The authentication configuration. If - specified, service will use the authentication - configuration during scanning. - user_agent (google.cloud.websecurityscanner_v1beta.types.ScanConfig.UserAgent): - The user agent used during scanning. - blacklist_patterns (Sequence[str]): - The blacklist URL patterns as described in - https://cloud.google.com/security- - scanner/docs/excluded-urls - schedule (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Schedule): - The schedule of the ScanConfig. - target_platforms (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig.TargetPlatform]): - Set of Cloud Platforms targeted by the scan. If empty, - APP_ENGINE will be used as a default. - export_to_security_command_center (google.cloud.websecurityscanner_v1beta.types.ScanConfig.ExportToSecurityCommandCenter): - Controls export of scan configurations and - results to Cloud Security Command Center. - latest_run (google.cloud.websecurityscanner_v1beta.types.ScanRun): - Latest ScanRun if available. - risk_level (google.cloud.websecurityscanner_v1beta.types.ScanConfig.RiskLevel): - The risk level selected for the scan - """ - class UserAgent(proto.Enum): - r"""Type of user agents used for scanning.""" - USER_AGENT_UNSPECIFIED = 0 - CHROME_LINUX = 1 - CHROME_ANDROID = 2 - SAFARI_IPHONE = 3 - - class TargetPlatform(proto.Enum): - r"""Cloud platforms supported by Cloud Web Security Scanner.""" - TARGET_PLATFORM_UNSPECIFIED = 0 - APP_ENGINE = 1 - COMPUTE = 2 - - class RiskLevel(proto.Enum): - r"""Scan risk levels supported by Cloud Web Security Scanner. LOW - impact scanning will minimize requests with the potential to - modify data. To achieve the maximum scan coverage, NORMAL risk - level is recommended. - """ - RISK_LEVEL_UNSPECIFIED = 0 - NORMAL = 1 - LOW = 2 - - class ExportToSecurityCommandCenter(proto.Enum): - r"""Controls export of scan configurations and results to Cloud - Security Command Center. - """ - EXPORT_TO_SECURITY_COMMAND_CENTER_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - class Authentication(proto.Message): - r"""Scan authentication configuration. - Attributes: - google_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.GoogleAccount): - Authentication using a Google account. - custom_account (google.cloud.websecurityscanner_v1beta.types.ScanConfig.Authentication.CustomAccount): - Authentication using a custom account. - """ - - class GoogleAccount(proto.Message): - r"""Describes authentication configuration that uses a Google - account. - - Attributes: - username (str): - Required. The user name of the Google - account. - password (str): - Required. Input only. The password of the - Google account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - """ - - username = proto.Field( - proto.STRING, - number=1, - ) - password = proto.Field( - proto.STRING, - number=2, - ) - - class CustomAccount(proto.Message): - r"""Describes authentication configuration that uses a custom - account. - - Attributes: - username (str): - Required. The user name of the custom - account. - password (str): - Required. Input only. The password of the - custom account. The credential is stored - encrypted and not returned in any response nor - included in audit logs. - login_url (str): - Required. The login form URL of the website. - """ - - username = proto.Field( - proto.STRING, - number=1, - ) - password = proto.Field( - proto.STRING, - number=2, - ) - login_url = proto.Field( - proto.STRING, - number=3, - ) - - google_account = proto.Field( - proto.MESSAGE, - number=1, - oneof='authentication', - message='ScanConfig.Authentication.GoogleAccount', - ) - custom_account = proto.Field( - proto.MESSAGE, - number=2, - oneof='authentication', - message='ScanConfig.Authentication.CustomAccount', - ) - - class Schedule(proto.Message): - r"""Scan schedule configuration. - Attributes: - schedule_time (google.protobuf.timestamp_pb2.Timestamp): - A timestamp indicates when the next run will - be scheduled. The value is refreshed by the - server after each run. If unspecified, it will - default to current server time, which means the - scan will be scheduled to start immediately. - interval_duration_days (int): - Required. The duration of time between - executions in days. - """ - - schedule_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - interval_duration_days = proto.Field( - proto.INT32, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - max_qps = proto.Field( - proto.INT32, - number=3, - ) - starting_urls = proto.RepeatedField( - proto.STRING, - number=4, - ) - authentication = proto.Field( - proto.MESSAGE, - number=5, - message=Authentication, - ) - user_agent = proto.Field( - proto.ENUM, - number=6, - enum=UserAgent, - ) - blacklist_patterns = proto.RepeatedField( - proto.STRING, - number=7, - ) - schedule = proto.Field( - proto.MESSAGE, - number=8, - message=Schedule, - ) - target_platforms = proto.RepeatedField( - proto.ENUM, - number=9, - enum=TargetPlatform, - ) - export_to_security_command_center = proto.Field( - proto.ENUM, - number=10, - enum=ExportToSecurityCommandCenter, - ) - latest_run = proto.Field( - proto.MESSAGE, - number=11, - message=scan_run.ScanRun, - ) - risk_level = proto.Field( - proto.ENUM, - number=12, - enum=RiskLevel, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py deleted file mode 100644 index af14d7c..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_config_error.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanConfigError', - }, -) - - -class ScanConfigError(proto.Message): - r"""Defines a custom error message used by CreateScanConfig and - UpdateScanConfig APIs when scan configuration validation fails. - It is also reported as part of a ScanRunErrorTrace message if - scan validation fails due to a scan configuration error. - - Attributes: - code (google.cloud.websecurityscanner_v1beta.types.ScanConfigError.Code): - Indicates the reason code for a configuration - failure. - field_name (str): - Indicates the full name of the ScanConfig field that - triggers this error, for example "scan_config.max_qps". This - field is provided for troubleshooting purposes only and its - actual value can change in the future. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 44 - """ - _pb_options = {'allow_alias': True} - CODE_UNSPECIFIED = 0 - OK = 0 - INTERNAL_ERROR = 1 - APPENGINE_API_BACKEND_ERROR = 2 - APPENGINE_API_NOT_ACCESSIBLE = 3 - APPENGINE_DEFAULT_HOST_MISSING = 4 - CANNOT_USE_GOOGLE_COM_ACCOUNT = 6 - CANNOT_USE_OWNER_ACCOUNT = 7 - COMPUTE_API_BACKEND_ERROR = 8 - COMPUTE_API_NOT_ACCESSIBLE = 9 - CUSTOM_LOGIN_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 10 - CUSTOM_LOGIN_URL_MALFORMED = 11 - CUSTOM_LOGIN_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 12 - CUSTOM_LOGIN_URL_MAPPED_TO_UNRESERVED_ADDRESS = 13 - CUSTOM_LOGIN_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 14 - CUSTOM_LOGIN_URL_HAS_UNRESERVED_IP_ADDRESS = 15 - DUPLICATE_SCAN_NAME = 16 - INVALID_FIELD_VALUE = 18 - FAILED_TO_AUTHENTICATE_TO_TARGET = 19 - FINDING_TYPE_UNSPECIFIED = 20 - FORBIDDEN_TO_SCAN_COMPUTE = 21 - FORBIDDEN_UPDATE_TO_MANAGED_SCAN = 43 - MALFORMED_FILTER = 22 - MALFORMED_RESOURCE_NAME = 23 - PROJECT_INACTIVE = 24 - REQUIRED_FIELD = 25 - RESOURCE_NAME_INCONSISTENT = 26 - SCAN_ALREADY_RUNNING = 27 - SCAN_NOT_RUNNING = 28 - SEED_URL_DOES_NOT_BELONG_TO_CURRENT_PROJECT = 29 - SEED_URL_MALFORMED = 30 - SEED_URL_MAPPED_TO_NON_ROUTABLE_ADDRESS = 31 - SEED_URL_MAPPED_TO_UNRESERVED_ADDRESS = 32 - SEED_URL_HAS_NON_ROUTABLE_IP_ADDRESS = 33 - SEED_URL_HAS_UNRESERVED_IP_ADDRESS = 35 - SERVICE_ACCOUNT_NOT_CONFIGURED = 36 - TOO_MANY_SCANS = 37 - UNABLE_TO_RESOLVE_PROJECT_INFO = 38 - UNSUPPORTED_BLACKLIST_PATTERN_FORMAT = 39 - UNSUPPORTED_FILTER = 40 - UNSUPPORTED_FINDING_TYPE = 41 - UNSUPPORTED_URL_SCHEME = 42 - - code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - field_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py deleted file mode 100644 index c7ddcee..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanRun', - }, -) - - -class ScanRun(proto.Message): - r"""A ScanRun is a output-only resource representing an actual - run of the scan. Next id: 12 - - Attributes: - name (str): - The resource name of the ScanRun. The name - follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - The ScanRun IDs are generated by the system. - execution_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ExecutionState): - The execution state of the ScanRun. - result_state (google.cloud.websecurityscanner_v1beta.types.ScanRun.ResultState): - The result state of the ScanRun. This field - is only available after the execution state - reaches "FINISHED". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the ScanRun reached - termination state - that the ScanRun is either - finished or stopped by user. - urls_crawled_count (int): - The number of URLs crawled during this - ScanRun. If the scan is in progress, the value - represents the number of URLs crawled up to now. - urls_tested_count (int): - The number of URLs tested during this - ScanRun. If the scan is in progress, the value - represents the number of URLs tested up to now. - The number of URLs tested is usually larger than - the number URLS crawled because typically a - crawled URL is tested with multiple test - payloads. - has_vulnerabilities (bool): - Whether the scan run has found any - vulnerabilities. - progress_percent (int): - The percentage of total completion ranging - from 0 to 100. If the scan is in queue, the - value is 0. If the scan is running, the value - ranges from 0 to 100. If the scan is finished, - the value is 100. - error_trace (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace): - If result_state is an ERROR, this field provides the primary - reason for scan's termination and more details, if such are - available. - warning_traces (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace]): - A list of warnings, if such are encountered - during this scan run. - """ - class ExecutionState(proto.Enum): - r"""Types of ScanRun execution state.""" - EXECUTION_STATE_UNSPECIFIED = 0 - QUEUED = 1 - SCANNING = 2 - FINISHED = 3 - - class ResultState(proto.Enum): - r"""Types of ScanRun result state.""" - RESULT_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - ERROR = 2 - KILLED = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - execution_state = proto.Field( - proto.ENUM, - number=2, - enum=ExecutionState, - ) - result_state = proto.Field( - proto.ENUM, - number=3, - enum=ResultState, - ) - start_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - urls_crawled_count = proto.Field( - proto.INT64, - number=6, - ) - urls_tested_count = proto.Field( - proto.INT64, - number=7, - ) - has_vulnerabilities = proto.Field( - proto.BOOL, - number=8, - ) - progress_percent = proto.Field( - proto.INT32, - number=9, - ) - error_trace = proto.Field( - proto.MESSAGE, - number=10, - message=scan_run_error_trace.ScanRunErrorTrace, - ) - warning_traces = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=scan_run_warning_trace.ScanRunWarningTrace, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py deleted file mode 100644 index 8f172dc..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_error_trace.py +++ /dev/null @@ -1,75 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import scan_config_error as gcw_scan_config_error - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanRunErrorTrace', - }, -) - - -class ScanRunErrorTrace(proto.Message): - r"""Output only. - Defines an error trace message for a ScanRun. - - Attributes: - code (google.cloud.websecurityscanner_v1beta.types.ScanRunErrorTrace.Code): - Indicates the error reason code. - scan_config_error (google.cloud.websecurityscanner_v1beta.types.ScanConfigError): - If the scan encounters SCAN_CONFIG_ISSUE error, this field - has the error message encountered during scan configuration - validation that is performed before each scan run. - most_common_http_error_code (int): - If the scan encounters TOO_MANY_HTTP_ERRORS, this field - indicates the most common HTTP error code, if such is - available. For example, if this code is 404, the scan has - encountered too many NOT_FOUND responses. - """ - class Code(proto.Enum): - r"""Output only. - Defines an error reason code. - Next id: 7 - """ - CODE_UNSPECIFIED = 0 - INTERNAL_ERROR = 1 - SCAN_CONFIG_ISSUE = 2 - AUTHENTICATION_CONFIG_ISSUE = 3 - TIMED_OUT_WHILE_SCANNING = 4 - TOO_MANY_REDIRECTS = 5 - TOO_MANY_HTTP_ERRORS = 6 - - code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - scan_config_error = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config_error.ScanConfigError, - ) - most_common_http_error_code = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py deleted file mode 100644 index 45ef967..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/scan_run_warning_trace.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'ScanRunWarningTrace', - }, -) - - -class ScanRunWarningTrace(proto.Message): - r"""Output only. - Defines a warning trace message for ScanRun. Warning traces - provide customers with useful information that helps make the - scanning process more effective. - - Attributes: - code (google.cloud.websecurityscanner_v1beta.types.ScanRunWarningTrace.Code): - Indicates the warning code. - """ - class Code(proto.Enum): - r"""Output only. - Defines a warning message code. - Next id: 6 - """ - CODE_UNSPECIFIED = 0 - INSUFFICIENT_CRAWL_RESULTS = 1 - TOO_MANY_CRAWL_RESULTS = 2 - TOO_MANY_FUZZ_TASKS = 3 - BLOCKED_BY_IAP = 4 - - code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py b/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py deleted file mode 100644 index 04dcf8f..0000000 --- a/owl-bot-staging/v1beta/google/cloud/websecurityscanner_v1beta/types/web_security_scanner.py +++ /dev/null @@ -1,463 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats as gcw_finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.websecurityscanner.v1beta', - manifest={ - 'CreateScanConfigRequest', - 'DeleteScanConfigRequest', - 'GetScanConfigRequest', - 'ListScanConfigsRequest', - 'UpdateScanConfigRequest', - 'ListScanConfigsResponse', - 'StartScanRunRequest', - 'GetScanRunRequest', - 'ListScanRunsRequest', - 'ListScanRunsResponse', - 'StopScanRunRequest', - 'ListCrawledUrlsRequest', - 'ListCrawledUrlsResponse', - 'GetFindingRequest', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListFindingTypeStatsRequest', - 'ListFindingTypeStatsResponse', - }, -) - - -class CreateScanConfigRequest(proto.Message): - r"""Request for the ``CreateScanConfig`` method. - Attributes: - parent (str): - Required. The parent resource name where the - scan is created, which should be a project - resource name in the format - 'projects/{projectId}'. - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be created. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - scan_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - - -class DeleteScanConfigRequest(proto.Message): - r"""Request for the ``DeleteScanConfig`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be deleted. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanConfigRequest(proto.Message): - r"""Request for the ``GetScanConfig`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanConfigsRequest(proto.Message): - r"""Request for the ``ListScanConfigs`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a project resource name in the format - 'projects/{projectId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanConfigs to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class UpdateScanConfigRequest(proto.Message): - r"""Request for the ``UpdateScanConfigRequest`` method. - Attributes: - scan_config (google.cloud.websecurityscanner_v1beta.types.ScanConfig): - Required. The ScanConfig to be updated. The - name field must be set to identify the resource - to be updated. The values of fields not covered - by the mask will be ignored. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The update mask applies to the resource. For the - ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask - """ - - scan_config = proto.Field( - proto.MESSAGE, - number=2, - message=gcw_scan_config.ScanConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListScanConfigsResponse(proto.Message): - r"""Response for the ``ListScanConfigs`` method. - Attributes: - scan_configs (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanConfig]): - The list of ScanConfigs returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_scan_config.ScanConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class StartScanRunRequest(proto.Message): - r"""Request for the ``StartScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanConfig - to be used. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetScanRunRequest(proto.Message): - r"""Request for the ``GetScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanRun to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListScanRunsRequest(proto.Message): - r"""Request for the ``ListScanRuns`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of ScanRuns to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListScanRunsResponse(proto.Message): - r"""Response for the ``ListScanRuns`` method. - Attributes: - scan_runs (Sequence[google.cloud.websecurityscanner_v1beta.types.ScanRun]): - The list of ScanRuns returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - scan_runs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=scan_run.ScanRun, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class StopScanRunRequest(proto.Message): - r"""Request for the ``StopScanRun`` method. - Attributes: - name (str): - Required. The resource name of the ScanRun to - be stopped. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListCrawledUrlsRequest(proto.Message): - r"""Request for the ``ListCrawledUrls`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of CrawledUrls to return, - can be limited by server. If not specified or - not positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCrawledUrlsResponse(proto.Message): - r"""Response for the ``ListCrawledUrls`` method. - Attributes: - crawled_urls (Sequence[google.cloud.websecurityscanner_v1beta.types.CrawledUrl]): - The list of CrawledUrls returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - crawled_urls = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=crawled_url.CrawledUrl, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFindingRequest(proto.Message): - r"""Request for the ``GetFinding`` method. - Attributes: - name (str): - Required. The resource name of the Finding to - be returned. The name follows the format of - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}/findings/{findingId}'. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request for the ``ListFindings`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - filter (str): - Required. The filter expression. The expression must be in - the format: . Supported field: 'finding_type'. Supported - operator: '='. - page_token (str): - A token identifying a page of results to be returned. This - should be a ``next_page_token`` value returned from a - previous List request. If unspecified, the first page of - results is returned. - page_size (int): - The maximum number of Findings to return, can - be limited by server. If not specified or not - positive, the implementation will select a - reasonable value. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response for the ``ListFindings`` method. - Attributes: - findings (Sequence[google.cloud.websecurityscanner_v1beta.types.Finding]): - The list of Findings returned. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - """ - - @property - def raw_page(self): - return self - - findings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=finding.Finding, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingTypeStatsRequest(proto.Message): - r"""Request for the ``ListFindingTypeStats`` method. - Attributes: - parent (str): - Required. The parent resource name, which - should be a scan run resource name in the format - 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFindingTypeStatsResponse(proto.Message): - r"""Response for the ``ListFindingTypeStats`` method. - Attributes: - finding_type_stats (Sequence[google.cloud.websecurityscanner_v1beta.types.FindingTypeStats]): - The list of FindingTypeStats returned. - """ - - finding_type_stats = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcw_finding_type_stats.FindingTypeStats, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta/mypy.ini b/owl-bot-staging/v1beta/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta/noxfile.py b/owl-bot-staging/v1beta/noxfile.py deleted file mode 100644 index 4ca1ea6..0000000 --- a/owl-bot-staging/v1beta/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/websecurityscanner_v1beta/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py b/owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py deleted file mode 100644 index 5dd19da..0000000 --- a/owl-bot-staging/v1beta/scripts/fixup_websecurityscanner_v1beta_keywords.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class websecurityscannerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', '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: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=websecurityscannerCallTransformer(), -): - """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 websecurityscanner client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta/setup.py b/owl-bot-staging/v1beta/setup.py deleted file mode 100644 index a33245a..0000000 --- a/owl-bot-staging/v1beta/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-websecurityscanner', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta/tests/__init__.py b/owl-bot-staging/v1beta/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta/tests/unit/__init__.py b/owl-bot-staging/v1beta/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py b/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py b/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py deleted file mode 100644 index e5c9073..0000000 --- a/owl-bot-staging/v1beta/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py +++ /dev/null @@ -1,4961 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerAsyncClient -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import WebSecurityScannerClient -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import pagers -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import transports -from google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.websecurityscanner_v1beta.types import crawled_url -from google.cloud.websecurityscanner_v1beta.types import finding -from google.cloud.websecurityscanner_v1beta.types import finding_addon -from google.cloud.websecurityscanner_v1beta.types import finding_type_stats -from google.cloud.websecurityscanner_v1beta.types import scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config -from google.cloud.websecurityscanner_v1beta.types import scan_config_error -from google.cloud.websecurityscanner_v1beta.types import scan_run -from google.cloud.websecurityscanner_v1beta.types import scan_run_error_trace -from google.cloud.websecurityscanner_v1beta.types import scan_run_warning_trace -from google.cloud.websecurityscanner_v1beta.types import web_security_scanner -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert WebSecurityScannerClient._get_default_mtls_endpoint(None) is None - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebSecurityScannerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - WebSecurityScannerClient, - WebSecurityScannerAsyncClient, -]) -def test_web_security_scanner_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WebSecurityScannerGrpcTransport, "grpc"), - (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - WebSecurityScannerClient, - WebSecurityScannerAsyncClient, -]) -def test_web_security_scanner_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -def test_web_security_scanner_client_get_transport_class(): - transport = WebSecurityScannerClient.get_transport_class() - available_transports = [ - transports.WebSecurityScannerGrpcTransport, - ] - assert transport in available_transports - - transport = WebSecurityScannerClient.get_transport_class("grpc") - assert transport == transports.WebSecurityScannerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -def test_web_security_scanner_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(WebSecurityScannerClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(WebSecurityScannerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "true"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc", "false"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(WebSecurityScannerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerClient)) -@mock.patch.object(WebSecurityScannerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebSecurityScannerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_web_security_scanner_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebSecurityScannerClient, transports.WebSecurityScannerGrpcTransport, "grpc"), - (WebSecurityScannerAsyncClient, transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_web_security_scanner_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_web_security_scanner_client_client_options_from_dict(): - with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebSecurityScannerClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_create_scan_config(transport: str = 'grpc', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - ) - response = client.create_scan_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] == web_security_scanner.CreateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -def test_create_scan_config_from_dict(): - test_create_scan_config(request_type=dict) - - -def test_create_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - client.create_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest() - - -@pytest.mark.asyncio -async def test_create_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.CreateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - )) - response = await client.create_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.CreateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.asyncio -async def test_create_scan_config_async_from_dict(): - await test_create_scan_config_async(request_type=dict) - - -def test_create_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.create_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.CreateScanConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.create_scan_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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') - - -def test_create_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_scan_config( - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(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].scan_config == gcw_scan_config.ScanConfig(name='name_value') - - -@pytest.mark.asyncio -async def test_create_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_scan_config( - web_security_scanner.CreateScanConfigRequest(), - parent='parent_value', - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - ) - - -def test_delete_scan_config(transport: str = 'grpc', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_scan_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] == web_security_scanner.DeleteScanConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_scan_config_from_dict(): - test_delete_scan_config(request_type=dict) - - -def test_delete_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - client.delete_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest() - - -@pytest.mark.asyncio -async def test_delete_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.DeleteScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.DeleteScanConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_scan_config_async_from_dict(): - await test_delete_scan_config_async(request_type=dict) - - -def test_delete_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = None - client.delete_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.DeleteScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_scan_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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_scan_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_scan_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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_scan_config( - web_security_scanner.DeleteScanConfigRequest(), - name='name_value', - ) - - -def test_get_scan_config(transport: str = 'grpc', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - ) - response = client.get_scan_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] == web_security_scanner.GetScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - - -def test_get_scan_config_from_dict(): - test_get_scan_config(request_type=dict) - - -def test_get_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - client.get_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest() - - -@pytest.mark.asyncio -async def test_get_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, - )) - response = await client.get_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.asyncio -async def test_get_scan_config_async_from_dict(): - await test_get_scan_config_async(request_type=dict) - - -def test_get_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = scan_config.ScanConfig() - client.get_scan_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_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - await client.get_scan_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_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_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_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_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_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_scan_config( - web_security_scanner.GetScanConfigRequest(), - name='name_value', - ) - - -def test_list_scan_configs(transport: str = 'grpc', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_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] == web_security_scanner.ListScanConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_configs_from_dict(): - test_list_scan_configs(request_type=dict) - - -def test_list_scan_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - client.list_scan_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest() - - -@pytest.mark.asyncio -async def test_list_scan_configs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanConfigsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_configs_async_from_dict(): - await test_list_scan_configs_async(request_type=dict) - - -def test_list_scan_configs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanConfigsResponse() - client.list_scan_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_scan_configs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - await client.list_scan_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_scan_configs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_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_scan_configs_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_scan_configs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_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_scan_configs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_scan_configs( - web_security_scanner.ListScanConfigsRequest(), - parent='parent_value', - ) - - -def test_list_scan_configs_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_configs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, scan_config.ScanConfig) - for i in results) - -def test_list_scan_configs_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_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_scan_configs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_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, scan_config.ScanConfig) - for i in responses) - -@pytest.mark.asyncio -async def test_list_scan_configs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[], - next_page_token='def', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanConfigsResponse( - scan_configs=[ - scan_config.ScanConfig(), - scan_config.ScanConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_scan_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_update_scan_config(transport: str = 'grpc', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - ) - response = client.update_scan_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] == web_security_scanner.UpdateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -def test_update_scan_config_from_dict(): - test_update_scan_config(request_type=dict) - - -def test_update_scan_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - client.update_scan_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest() - - -@pytest.mark.asyncio -async def test_update_scan_config_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.UpdateScanConfigRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig( - name='name_value', - display_name='display_name_value', - max_qps=761, - starting_urls=['starting_urls_value'], - user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, - blacklist_patterns=['blacklist_patterns_value'], - target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], - export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, - risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, - )) - response = await client.update_scan_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.UpdateScanConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcw_scan_config.ScanConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.max_qps == 761 - assert response.starting_urls == ['starting_urls_value'] - assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX - assert response.blacklist_patterns == ['blacklist_patterns_value'] - assert response.target_platforms == [gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE] - assert response.export_to_security_command_center == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED - assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL - - -@pytest.mark.asyncio -async def test_update_scan_config_async_from_dict(): - await test_update_scan_config_async(request_type=dict) - - -def test_update_scan_config_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'scan_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = gcw_scan_config.ScanConfig() - client.update_scan_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', - 'scan_config.name=scan_config.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_scan_config_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.UpdateScanConfigRequest() - - request.scan_config.name = 'scan_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - await client.update_scan_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', - 'scan_config.name=scan_config.name/value', - ) in kw['metadata'] - - -def test_update_scan_config_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_scan_config_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_scan_config_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_scan_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcw_scan_config.ScanConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcw_scan_config.ScanConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_scan_config( - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].scan_config == gcw_scan_config.ScanConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_scan_config_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_scan_config( - web_security_scanner.UpdateScanConfigRequest(), - scan_config=gcw_scan_config.ScanConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_start_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_start_scan_run_from_dict(): - test_start_scan_run(request_type=dict) - - -def test_start_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - client.start_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - -@pytest.mark.asyncio -async def test_start_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StartScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StartScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_start_scan_run_async_from_dict(): - await test_start_scan_run_async(request_type=dict) - - -def test_start_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_start_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StartScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.start_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_start_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_scan_run( - 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_start_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_start_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_scan_run( - 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_start_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_scan_run( - web_security_scanner.StartScanRunRequest(), - name='name_value', - ) - - -def test_get_scan_run(transport: str = 'grpc', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_get_scan_run_from_dict(): - test_get_scan_run(request_type=dict) - - -def test_get_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - client.get_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - -@pytest.mark.asyncio -async def test_get_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_get_scan_run_async_from_dict(): - await test_get_scan_run_async(request_type=dict) - - -def test_get_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.get_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_scan_run( - 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_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_scan_run( - 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_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_scan_run( - web_security_scanner.GetScanRunRequest(), - name='name_value', - ) - - -def test_list_scan_runs(transport: str = 'grpc', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_scan_runs_from_dict(): - test_list_scan_runs(request_type=dict) - - -def test_list_scan_runs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - client.list_scan_runs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - -@pytest.mark.asyncio -async def test_list_scan_runs_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListScanRunsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListScanRunsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListScanRunsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_scan_runs_async_from_dict(): - await test_list_scan_runs_async(request_type=dict) - - -def test_list_scan_runs_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = web_security_scanner.ListScanRunsResponse() - client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_scan_runs_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListScanRunsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - await client.list_scan_runs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_scan_runs_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_scan_runs( - 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_scan_runs_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_scan_runs_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListScanRunsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListScanRunsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_scan_runs( - 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_scan_runs_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_scan_runs( - web_security_scanner.ListScanRunsRequest(), - parent='parent_value', - ) - - -def test_list_scan_runs_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_scan_runs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, scan_run.ScanRun) - for i in results) - -def test_list_scan_runs_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = list(client.list_scan_runs(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_scan_runs_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_scan_runs(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, scan_run.ScanRun) - for i in responses) - -@pytest.mark.asyncio -async def test_list_scan_runs_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_scan_runs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - next_page_token='abc', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[], - next_page_token='def', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListScanRunsResponse( - scan_runs=[ - scan_run.ScanRun(), - scan_run.ScanRun(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_scan_runs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_stop_scan_run(transport: str = 'grpc', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - ) - response = client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -def test_stop_scan_run_from_dict(): - test_stop_scan_run(request_type=dict) - - -def test_stop_scan_run_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - client.stop_scan_run() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - -@pytest.mark.asyncio -async def test_stop_scan_run_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.StopScanRunRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun( - name='name_value', - execution_state=scan_run.ScanRun.ExecutionState.QUEUED, - result_state=scan_run.ScanRun.ResultState.SUCCESS, - urls_crawled_count=1935, - urls_tested_count=1846, - has_vulnerabilities=True, - progress_percent=1733, - )) - response = await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.StopScanRunRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, scan_run.ScanRun) - assert response.name == 'name_value' - assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED - assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS - assert response.urls_crawled_count == 1935 - assert response.urls_tested_count == 1846 - assert response.has_vulnerabilities is True - assert response.progress_percent == 1733 - - -@pytest.mark.asyncio -async def test_stop_scan_run_async_from_dict(): - await test_stop_scan_run_async(request_type=dict) - - -def test_stop_scan_run_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = scan_run.ScanRun() - client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_stop_scan_run_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.StopScanRunRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - await client.stop_scan_run(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_stop_scan_run_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_scan_run( - 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_stop_scan_run_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_stop_scan_run_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_scan_run), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = scan_run.ScanRun() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(scan_run.ScanRun()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_scan_run( - 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_stop_scan_run_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_scan_run( - web_security_scanner.StopScanRunRequest(), - name='name_value', - ) - - -def test_list_crawled_urls(transport: str = 'grpc', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_crawled_urls_from_dict(): - test_list_crawled_urls(request_type=dict) - - -def test_list_crawled_urls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - client.list_crawled_urls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListCrawledUrlsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListCrawledUrlsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCrawledUrlsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_from_dict(): - await test_list_crawled_urls_async(request_type=dict) - - -def test_list_crawled_urls_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_crawled_urls_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListCrawledUrlsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - await client.list_crawled_urls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_crawled_urls_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crawled_urls( - 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_crawled_urls_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_crawled_urls_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListCrawledUrlsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListCrawledUrlsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crawled_urls( - 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_crawled_urls_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_crawled_urls( - web_security_scanner.ListCrawledUrlsRequest(), - parent='parent_value', - ) - - -def test_list_crawled_urls_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crawled_urls(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, crawled_url.CrawledUrl) - for i in results) - -def test_list_crawled_urls_pages(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crawled_urls(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_crawled_urls_async_pager(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crawled_urls(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, crawled_url.CrawledUrl) - for i in responses) - -@pytest.mark.asyncio -async def test_list_crawled_urls_async_pages(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crawled_urls), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - next_page_token='abc', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[], - next_page_token='def', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - ], - next_page_token='ghi', - ), - web_security_scanner.ListCrawledUrlsResponse( - crawled_urls=[ - crawled_url.CrawledUrl(), - crawled_url.CrawledUrl(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_crawled_urls(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_finding(transport: str = 'grpc', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - finding_type='finding_type_value', - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - ) - response = client.get_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] == web_security_scanner.GetFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -def test_get_finding_from_dict(): - test_get_finding(request_type=dict) - - -def test_get_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - client.get_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest() - - -@pytest.mark.asyncio -async def test_get_finding_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.GetFindingRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - finding_type='finding_type_value', - http_method='http_method_value', - fuzzed_url='fuzzed_url_value', - body='body_value', - description='description_value', - reproduction_url='reproduction_url_value', - frame_url='frame_url_value', - final_url='final_url_value', - tracking_id='tracking_id_value', - )) - response = await client.get_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.GetFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.finding_type == 'finding_type_value' - assert response.http_method == 'http_method_value' - assert response.fuzzed_url == 'fuzzed_url_value' - assert response.body == 'body_value' - assert response.description == 'description_value' - assert response.reproduction_url == 'reproduction_url_value' - assert response.frame_url == 'frame_url_value' - assert response.final_url == 'final_url_value' - assert response.tracking_id == 'tracking_id_value' - - -@pytest.mark.asyncio -async def test_get_finding_async_from_dict(): - await test_get_finding_async(request_type=dict) - - -def test_get_finding_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = finding.Finding() - client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_finding_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.GetFindingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.get_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', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_finding_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__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.get_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].name == 'name_value' - - -def test_get_finding_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_finding_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_finding), - '__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.get_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].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_finding_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_finding( - web_security_scanner.GetFindingRequest(), - name='name_value', - ) - - -def test_list_findings(transport: str = 'grpc', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - ) - 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] == web_security_scanner.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' - - -def test_list_findings_from_dict(): - test_list_findings(request_type=dict) - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingsRequest() - - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingsResponse( - next_page_token='next_page_token_value', - )) - 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] == web_security_scanner.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - - -def test_list_findings_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.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 = web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.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', - filter='filter_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].filter == 'filter_value' - - -def test_list_findings_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.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', - filter='filter_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].filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_list_findings_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_findings( - web_security_scanner.ListFindingsRequest(), - parent='parent_value', - filter='filter_value', - ) - - -def test_list_findings_pager(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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 = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - web_security_scanner.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - web_security_scanner.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - web_security_scanner.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_finding_type_stats(transport: str = 'grpc', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse( - ) - response = client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -def test_list_finding_type_stats_from_dict(): - test_list_finding_type_stats(request_type=dict) - - -def test_list_finding_type_stats_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - client.list_finding_type_stats() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async(transport: str = 'grpc_asyncio', request_type=web_security_scanner.ListFindingTypeStatsRequest): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse( - )) - response = await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == web_security_scanner.ListFindingTypeStatsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_async_from_dict(): - await test_list_finding_type_stats_async(request_type=dict) - - -def test_list_finding_type_stats_field_headers(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_finding_type_stats_field_headers_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = web_security_scanner.ListFindingTypeStatsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - await client.list_finding_type_stats(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_finding_type_stats_flattened(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_finding_type_stats( - 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_finding_type_stats_flattened_error(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_finding_type_stats_flattened_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_finding_type_stats), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = web_security_scanner.ListFindingTypeStatsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(web_security_scanner.ListFindingTypeStatsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_finding_type_stats( - 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_finding_type_stats_flattened_error_async(): - client = WebSecurityScannerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_finding_type_stats( - web_security_scanner.ListFindingTypeStatsRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_scan_config', - 'delete_scan_config', - 'get_scan_config', - 'list_scan_configs', - 'update_scan_config', - 'start_scan_run', - 'get_scan_run', - 'list_scan_runs', - 'stop_scan_run', - 'list_crawled_urls', - 'get_finding', - 'list_findings', - 'list_finding_type_stats', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - 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_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebSecurityScannerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebSecurityScannerClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_web_security_scanner_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_web_security_scanner_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebSecurityScannerGrpcTransport, grpc_helpers), - (transports.WebSecurityScannerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_web_security_scanner_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "websecurityscanner.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="websecurityscanner.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_web_security_scanner_host_no_port(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com'), - ) - assert client.transport._host == 'websecurityscanner.googleapis.com:443' - - -def test_web_security_scanner_host_with_port(): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='websecurityscanner.googleapis.com:8000'), - ) - assert client.transport._host == 'websecurityscanner.googleapis.com:8000' - -def test_web_security_scanner_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_web_security_scanner_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport]) -def test_web_security_scanner_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_finding_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - finding = "octopus" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}".format(project=project, scan_config=scan_config, scan_run=scan_run, finding=finding, ) - actual = WebSecurityScannerClient.finding_path(project, scan_config, scan_run, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "project": "oyster", - "scan_config": "nudibranch", - "scan_run": "cuttlefish", - "finding": "mussel", - } - path = WebSecurityScannerClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_finding_path(path) - assert expected == actual - -def test_scan_config_path(): - project = "winkle" - scan_config = "nautilus" - expected = "projects/{project}/scanConfigs/{scan_config}".format(project=project, scan_config=scan_config, ) - actual = WebSecurityScannerClient.scan_config_path(project, scan_config) - assert expected == actual - - -def test_parse_scan_config_path(): - expected = { - "project": "scallop", - "scan_config": "abalone", - } - path = WebSecurityScannerClient.scan_config_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_config_path(path) - assert expected == actual - -def test_scan_run_path(): - project = "squid" - scan_config = "clam" - scan_run = "whelk" - expected = "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}".format(project=project, scan_config=scan_config, scan_run=scan_run, ) - actual = WebSecurityScannerClient.scan_run_path(project, scan_config, scan_run) - assert expected == actual - - -def test_parse_scan_run_path(): - expected = { - "project": "octopus", - "scan_config": "oyster", - "scan_run": "nudibranch", - } - path = WebSecurityScannerClient.scan_run_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_scan_run_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebSecurityScannerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = WebSecurityScannerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebSecurityScannerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = WebSecurityScannerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebSecurityScannerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = WebSecurityScannerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = WebSecurityScannerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = WebSecurityScannerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = WebSecurityScannerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = WebSecurityScannerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebSecurityScannerClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebSecurityScannerTransport, '_prep_wrapped_messages') as prep: - transport_class = WebSecurityScannerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/scripts/fixup_websecurityscanner_v1_keywords.py b/scripts/fixup_websecurityscanner_v1_keywords.py index cdd5da0..5dd19da 100644 --- a/scripts/fixup_websecurityscanner_v1_keywords.py +++ b/scripts/fixup_websecurityscanner_v1_keywords.py @@ -39,19 +39,19 @@ def partition( class websecurityscannerCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', 'update_mask', ), + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -70,7 +70,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) diff --git a/scripts/fixup_websecurityscanner_v1alpha_keywords.py b/scripts/fixup_websecurityscanner_v1alpha_keywords.py index cdd5da0..5dd19da 100644 --- a/scripts/fixup_websecurityscanner_v1alpha_keywords.py +++ b/scripts/fixup_websecurityscanner_v1alpha_keywords.py @@ -39,19 +39,19 @@ def partition( class websecurityscannerCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', 'update_mask', ), + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -70,7 +70,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) diff --git a/scripts/fixup_websecurityscanner_v1beta_keywords.py b/scripts/fixup_websecurityscanner_v1beta_keywords.py index cdd5da0..5dd19da 100644 --- a/scripts/fixup_websecurityscanner_v1beta_keywords.py +++ b/scripts/fixup_websecurityscanner_v1beta_keywords.py @@ -39,19 +39,19 @@ def partition( class websecurityscannerCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_scan_config': ('parent', 'scan_config', ), - 'delete_scan_config': ('name', ), - 'get_finding': ('name', ), - 'get_scan_config': ('name', ), - 'get_scan_run': ('name', ), - 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_finding_type_stats': ('parent', ), - 'list_scan_configs': ('parent', 'page_token', 'page_size', ), - 'list_scan_runs': ('parent', 'page_token', 'page_size', ), - 'start_scan_run': ('name', ), - 'stop_scan_run': ('name', ), - 'update_scan_config': ('scan_config', 'update_mask', ), + 'create_scan_config': ('parent', 'scan_config', ), + 'delete_scan_config': ('name', ), + 'get_finding': ('name', ), + 'get_scan_config': ('name', ), + 'get_scan_run': ('name', ), + 'list_crawled_urls': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_finding_type_stats': ('parent', ), + 'list_scan_configs': ('parent', 'page_token', 'page_size', ), + 'list_scan_runs': ('parent', 'page_token', 'page_size', ), + 'start_scan_run': ('name', ), + 'stop_scan_run': ('name', ), + 'update_scan_config': ('scan_config', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -70,7 +70,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs )