diff --git a/appcheck_gapic/.coveragerc b/appcheck_gapic/.coveragerc new file mode 100644 index 000000000..3a3234929 --- /dev/null +++ b/appcheck_gapic/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/firebase/appcheck/__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/appcheck_gapic/MANIFEST.in b/appcheck_gapic/MANIFEST.in new file mode 100644 index 000000000..a719cdf01 --- /dev/null +++ b/appcheck_gapic/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/firebase/appcheck *.py +recursive-include google/firebase/appcheck_v1beta *.py diff --git a/appcheck_gapic/README.rst b/appcheck_gapic/README.rst new file mode 100644 index 000000000..047c50123 --- /dev/null +++ b/appcheck_gapic/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Firebase Appcheck 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 Firebase Appcheck 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/appcheck_gapic/docs/appcheck_v1beta/config_service.rst b/appcheck_gapic/docs/appcheck_v1beta/config_service.rst new file mode 100644 index 000000000..6c90ef18e --- /dev/null +++ b/appcheck_gapic/docs/appcheck_v1beta/config_service.rst @@ -0,0 +1,10 @@ +ConfigService +------------------------------- + +.. automodule:: google.firebase.appcheck_v1beta.services.config_service + :members: + :inherited-members: + +.. automodule:: google.firebase.appcheck_v1beta.services.config_service.pagers + :members: + :inherited-members: diff --git a/appcheck_gapic/docs/appcheck_v1beta/services.rst b/appcheck_gapic/docs/appcheck_v1beta/services.rst new file mode 100644 index 000000000..d585eaf7a --- /dev/null +++ b/appcheck_gapic/docs/appcheck_v1beta/services.rst @@ -0,0 +1,7 @@ +Services for Google Firebase Appcheck v1beta API +================================================ +.. toctree:: + :maxdepth: 2 + + config_service + token_exchange_service diff --git a/appcheck_gapic/docs/appcheck_v1beta/token_exchange_service.rst b/appcheck_gapic/docs/appcheck_v1beta/token_exchange_service.rst new file mode 100644 index 000000000..db8823a22 --- /dev/null +++ b/appcheck_gapic/docs/appcheck_v1beta/token_exchange_service.rst @@ -0,0 +1,6 @@ +TokenExchangeService +-------------------------------------- + +.. automodule:: google.firebase.appcheck_v1beta.services.token_exchange_service + :members: + :inherited-members: diff --git a/appcheck_gapic/docs/appcheck_v1beta/types.rst b/appcheck_gapic/docs/appcheck_v1beta/types.rst new file mode 100644 index 000000000..ef3ad7e07 --- /dev/null +++ b/appcheck_gapic/docs/appcheck_v1beta/types.rst @@ -0,0 +1,7 @@ +Types for Google Firebase Appcheck v1beta API +============================================= + +.. automodule:: google.firebase.appcheck_v1beta.types + :members: + :undoc-members: + :show-inheritance: diff --git a/appcheck_gapic/docs/conf.py b/appcheck_gapic/docs/conf.py new file mode 100644 index 000000000..4ce435d23 --- /dev/null +++ b/appcheck_gapic/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-firebase-appcheck 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-firebase-appcheck" +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 Firebase 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-firebase-appcheck-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-firebase-appcheck.tex", + u"google-firebase-appcheck 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-firebase-appcheck", + u"Google Firebase Appcheck 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-firebase-appcheck", + u"google-firebase-appcheck Documentation", + author, + "google-firebase-appcheck", + "GAPIC library for Google Firebase Appcheck 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/appcheck_gapic/docs/index.rst b/appcheck_gapic/docs/index.rst new file mode 100644 index 000000000..70484561c --- /dev/null +++ b/appcheck_gapic/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + appcheck_v1beta/services + appcheck_v1beta/types diff --git a/appcheck_gapic/google/firebase/appcheck/__init__.py b/appcheck_gapic/google/firebase/appcheck/__init__.py new file mode 100644 index 000000000..0f67a580f --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck/__init__.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.firebase.appcheck_v1beta.services.config_service.client import ConfigServiceClient +from google.firebase.appcheck_v1beta.services.token_exchange_service.client import TokenExchangeServiceClient + +from google.firebase.appcheck_v1beta.types.configuration import AppAttestConfig +from google.firebase.appcheck_v1beta.types.configuration import BatchGetAppAttestConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetAppAttestConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchGetDeviceCheckConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetDeviceCheckConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchGetRecaptchaConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetRecaptchaConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchGetSafetyNetConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetSafetyNetConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchUpdateServicesRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchUpdateServicesResponse +from google.firebase.appcheck_v1beta.types.configuration import CreateDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import DebugToken +from google.firebase.appcheck_v1beta.types.configuration import DeleteDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import DeviceCheckConfig +from google.firebase.appcheck_v1beta.types.configuration import GetAppAttestConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import GetDeviceCheckConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetRecaptchaConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetSafetyNetConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetServiceRequest +from google.firebase.appcheck_v1beta.types.configuration import ListDebugTokensRequest +from google.firebase.appcheck_v1beta.types.configuration import ListDebugTokensResponse +from google.firebase.appcheck_v1beta.types.configuration import ListServicesRequest +from google.firebase.appcheck_v1beta.types.configuration import ListServicesResponse +from google.firebase.appcheck_v1beta.types.configuration import RecaptchaConfig +from google.firebase.appcheck_v1beta.types.configuration import SafetyNetConfig +from google.firebase.appcheck_v1beta.types.configuration import Service +from google.firebase.appcheck_v1beta.types.configuration import UpdateAppAttestConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateDeviceCheckConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateRecaptchaConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateSafetyNetConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateServiceRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import AppAttestChallengeResponse +from google.firebase.appcheck_v1beta.types.token_exchange_service import AttestationTokenResponse +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeAppAttestAssertionRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeAppAttestAttestationRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeAppAttestAttestationResponse +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeCustomTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeDebugTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeDeviceCheckTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeRecaptchaTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeSafetyNetTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import GenerateAppAttestChallengeRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import GetPublicJwkSetRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import PublicJwk +from google.firebase.appcheck_v1beta.types.token_exchange_service import PublicJwkSet + +__all__ = ('ConfigServiceClient', + 'TokenExchangeServiceClient', + 'AppAttestConfig', + 'BatchGetAppAttestConfigsRequest', + 'BatchGetAppAttestConfigsResponse', + 'BatchGetDeviceCheckConfigsRequest', + 'BatchGetDeviceCheckConfigsResponse', + 'BatchGetRecaptchaConfigsRequest', + 'BatchGetRecaptchaConfigsResponse', + 'BatchGetSafetyNetConfigsRequest', + 'BatchGetSafetyNetConfigsResponse', + 'BatchUpdateServicesRequest', + 'BatchUpdateServicesResponse', + 'CreateDebugTokenRequest', + 'DebugToken', + 'DeleteDebugTokenRequest', + 'DeviceCheckConfig', + 'GetAppAttestConfigRequest', + 'GetDebugTokenRequest', + 'GetDeviceCheckConfigRequest', + 'GetRecaptchaConfigRequest', + 'GetSafetyNetConfigRequest', + 'GetServiceRequest', + 'ListDebugTokensRequest', + 'ListDebugTokensResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'RecaptchaConfig', + 'SafetyNetConfig', + 'Service', + 'UpdateAppAttestConfigRequest', + 'UpdateDebugTokenRequest', + 'UpdateDeviceCheckConfigRequest', + 'UpdateRecaptchaConfigRequest', + 'UpdateSafetyNetConfigRequest', + 'UpdateServiceRequest', + 'AppAttestChallengeResponse', + 'AttestationTokenResponse', + 'ExchangeAppAttestAssertionRequest', + 'ExchangeAppAttestAttestationRequest', + 'ExchangeAppAttestAttestationResponse', + 'ExchangeCustomTokenRequest', + 'ExchangeDebugTokenRequest', + 'ExchangeDeviceCheckTokenRequest', + 'ExchangeRecaptchaTokenRequest', + 'ExchangeSafetyNetTokenRequest', + 'GenerateAppAttestChallengeRequest', + 'GetPublicJwkSetRequest', + 'PublicJwk', + 'PublicJwkSet', +) diff --git a/appcheck_gapic/google/firebase/appcheck/py.typed b/appcheck_gapic/google/firebase/appcheck/py.typed new file mode 100644 index 000000000..c16f5d9cc --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-firebase-appcheck package uses inline types. diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/__init__.py new file mode 100644 index 000000000..eedc1ad9e --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/__init__.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.config_service import ConfigServiceClient +from .services.token_exchange_service import TokenExchangeServiceClient + +from .types.configuration import AppAttestConfig +from .types.configuration import BatchGetAppAttestConfigsRequest +from .types.configuration import BatchGetAppAttestConfigsResponse +from .types.configuration import BatchGetDeviceCheckConfigsRequest +from .types.configuration import BatchGetDeviceCheckConfigsResponse +from .types.configuration import BatchGetRecaptchaConfigsRequest +from .types.configuration import BatchGetRecaptchaConfigsResponse +from .types.configuration import BatchGetSafetyNetConfigsRequest +from .types.configuration import BatchGetSafetyNetConfigsResponse +from .types.configuration import BatchUpdateServicesRequest +from .types.configuration import BatchUpdateServicesResponse +from .types.configuration import CreateDebugTokenRequest +from .types.configuration import DebugToken +from .types.configuration import DeleteDebugTokenRequest +from .types.configuration import DeviceCheckConfig +from .types.configuration import GetAppAttestConfigRequest +from .types.configuration import GetDebugTokenRequest +from .types.configuration import GetDeviceCheckConfigRequest +from .types.configuration import GetRecaptchaConfigRequest +from .types.configuration import GetSafetyNetConfigRequest +from .types.configuration import GetServiceRequest +from .types.configuration import ListDebugTokensRequest +from .types.configuration import ListDebugTokensResponse +from .types.configuration import ListServicesRequest +from .types.configuration import ListServicesResponse +from .types.configuration import RecaptchaConfig +from .types.configuration import SafetyNetConfig +from .types.configuration import Service +from .types.configuration import UpdateAppAttestConfigRequest +from .types.configuration import UpdateDebugTokenRequest +from .types.configuration import UpdateDeviceCheckConfigRequest +from .types.configuration import UpdateRecaptchaConfigRequest +from .types.configuration import UpdateSafetyNetConfigRequest +from .types.configuration import UpdateServiceRequest +from .types.token_exchange_service import AppAttestChallengeResponse +from .types.token_exchange_service import AttestationTokenResponse +from .types.token_exchange_service import ExchangeAppAttestAssertionRequest +from .types.token_exchange_service import ExchangeAppAttestAttestationRequest +from .types.token_exchange_service import ExchangeAppAttestAttestationResponse +from .types.token_exchange_service import ExchangeCustomTokenRequest +from .types.token_exchange_service import ExchangeDebugTokenRequest +from .types.token_exchange_service import ExchangeDeviceCheckTokenRequest +from .types.token_exchange_service import ExchangeRecaptchaTokenRequest +from .types.token_exchange_service import ExchangeSafetyNetTokenRequest +from .types.token_exchange_service import GenerateAppAttestChallengeRequest +from .types.token_exchange_service import GetPublicJwkSetRequest +from .types.token_exchange_service import PublicJwk +from .types.token_exchange_service import PublicJwkSet + +__all__ = ( +'AppAttestChallengeResponse', +'AppAttestConfig', +'AttestationTokenResponse', +'BatchGetAppAttestConfigsRequest', +'BatchGetAppAttestConfigsResponse', +'BatchGetDeviceCheckConfigsRequest', +'BatchGetDeviceCheckConfigsResponse', +'BatchGetRecaptchaConfigsRequest', +'BatchGetRecaptchaConfigsResponse', +'BatchGetSafetyNetConfigsRequest', +'BatchGetSafetyNetConfigsResponse', +'BatchUpdateServicesRequest', +'BatchUpdateServicesResponse', +'ConfigServiceClient', +'CreateDebugTokenRequest', +'DebugToken', +'DeleteDebugTokenRequest', +'DeviceCheckConfig', +'ExchangeAppAttestAssertionRequest', +'ExchangeAppAttestAttestationRequest', +'ExchangeAppAttestAttestationResponse', +'ExchangeCustomTokenRequest', +'ExchangeDebugTokenRequest', +'ExchangeDeviceCheckTokenRequest', +'ExchangeRecaptchaTokenRequest', +'ExchangeSafetyNetTokenRequest', +'GenerateAppAttestChallengeRequest', +'GetAppAttestConfigRequest', +'GetDebugTokenRequest', +'GetDeviceCheckConfigRequest', +'GetPublicJwkSetRequest', +'GetRecaptchaConfigRequest', +'GetSafetyNetConfigRequest', +'GetServiceRequest', +'ListDebugTokensRequest', +'ListDebugTokensResponse', +'ListServicesRequest', +'ListServicesResponse', +'PublicJwk', +'PublicJwkSet', +'RecaptchaConfig', +'SafetyNetConfig', +'Service', +'TokenExchangeServiceClient', +'UpdateAppAttestConfigRequest', +'UpdateDebugTokenRequest', +'UpdateDeviceCheckConfigRequest', +'UpdateRecaptchaConfigRequest', +'UpdateSafetyNetConfigRequest', +'UpdateServiceRequest', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/gapic_metadata.json b/appcheck_gapic/google/firebase/appcheck_v1beta/gapic_metadata.json new file mode 100644 index 000000000..8b6aaa508 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/gapic_metadata.json @@ -0,0 +1,177 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.firebase.appcheck_v1beta", + "protoPackage": "google.firebase.appcheck.v1beta", + "schema": "1.0", + "services": { + "ConfigService": { + "clients": { + "rest": { + "libraryClient": "ConfigServiceClient", + "rpcs": { + "BatchGetAppAttestConfigs": { + "methods": [ + "batch_get_app_attest_configs" + ] + }, + "BatchGetDeviceCheckConfigs": { + "methods": [ + "batch_get_device_check_configs" + ] + }, + "BatchGetRecaptchaConfigs": { + "methods": [ + "batch_get_recaptcha_configs" + ] + }, + "BatchGetSafetyNetConfigs": { + "methods": [ + "batch_get_safety_net_configs" + ] + }, + "BatchUpdateServices": { + "methods": [ + "batch_update_services" + ] + }, + "CreateDebugToken": { + "methods": [ + "create_debug_token" + ] + }, + "DeleteDebugToken": { + "methods": [ + "delete_debug_token" + ] + }, + "GetAppAttestConfig": { + "methods": [ + "get_app_attest_config" + ] + }, + "GetDebugToken": { + "methods": [ + "get_debug_token" + ] + }, + "GetDeviceCheckConfig": { + "methods": [ + "get_device_check_config" + ] + }, + "GetRecaptchaConfig": { + "methods": [ + "get_recaptcha_config" + ] + }, + "GetSafetyNetConfig": { + "methods": [ + "get_safety_net_config" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListDebugTokens": { + "methods": [ + "list_debug_tokens" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateAppAttestConfig": { + "methods": [ + "update_app_attest_config" + ] + }, + "UpdateDebugToken": { + "methods": [ + "update_debug_token" + ] + }, + "UpdateDeviceCheckConfig": { + "methods": [ + "update_device_check_config" + ] + }, + "UpdateRecaptchaConfig": { + "methods": [ + "update_recaptcha_config" + ] + }, + "UpdateSafetyNetConfig": { + "methods": [ + "update_safety_net_config" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "TokenExchangeService": { + "clients": { + "rest": { + "libraryClient": "TokenExchangeServiceClient", + "rpcs": { + "ExchangeAppAttestAssertion": { + "methods": [ + "exchange_app_attest_assertion" + ] + }, + "ExchangeAppAttestAttestation": { + "methods": [ + "exchange_app_attest_attestation" + ] + }, + "ExchangeCustomToken": { + "methods": [ + "exchange_custom_token" + ] + }, + "ExchangeDebugToken": { + "methods": [ + "exchange_debug_token" + ] + }, + "ExchangeDeviceCheckToken": { + "methods": [ + "exchange_device_check_token" + ] + }, + "ExchangeRecaptchaToken": { + "methods": [ + "exchange_recaptcha_token" + ] + }, + "ExchangeSafetyNetToken": { + "methods": [ + "exchange_safety_net_token" + ] + }, + "GenerateAppAttestChallenge": { + "methods": [ + "generate_app_attest_challenge" + ] + }, + "GetPublicJwkSet": { + "methods": [ + "get_public_jwk_set" + ] + } + } + } + } + } + } +} diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/py.typed b/appcheck_gapic/google/firebase/appcheck_v1beta/py.typed new file mode 100644 index 000000000..c16f5d9cc --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-firebase-appcheck package uses inline types. diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_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/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/__init__.py new file mode 100644 index 000000000..7aaf88e2b --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/__init__.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ConfigServiceClient + +__all__ = ( + 'ConfigServiceClient', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/client.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/client.py new file mode 100644 index 000000000..c5de8c6cc --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/client.py @@ -0,0 +1,2467 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.firebase.appcheck_v1beta.services.config_service import pagers +from google.firebase.appcheck_v1beta.types import configuration +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.rest import ConfigServiceRestTransport + + +class ConfigServiceClientMeta(type): + """Metaclass for the ConfigService 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[ConfigServiceTransport]] + _transport_registry["rest"] = ConfigServiceRestTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ConfigServiceTransport]: + """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 ConfigServiceClient(metaclass=ConfigServiceClientMeta): + """Manages configuration parameters used by the + [TokenExchangeService][google.firebase.appcheck.v1beta.TokenExchangeService] + and enforcement settings for Firebase services protected by App + Check. + """ + + @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 = "firebaseappcheck.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: + ConfigServiceClient: 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: + ConfigServiceClient: 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) -> ConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def app_attest_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified app_attest_config string.""" + return "projects/{project}/apps/{app}/appAttestConfig".format(project=project, app=app, ) + + @staticmethod + def parse_app_attest_config_path(path: str) -> Dict[str,str]: + """Parses a app_attest_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/appAttestConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def debug_token_path(project: str,app: str,debug_token: str,) -> str: + """Returns a fully-qualified debug_token string.""" + return "projects/{project}/apps/{app}/debugTokens/{debug_token}".format(project=project, app=app, debug_token=debug_token, ) + + @staticmethod + def parse_debug_token_path(path: str) -> Dict[str,str]: + """Parses a debug_token path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/debugTokens/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def device_check_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified device_check_config string.""" + return "projects/{project}/apps/{app}/deviceCheckConfig".format(project=project, app=app, ) + + @staticmethod + def parse_device_check_config_path(path: str) -> Dict[str,str]: + """Parses a device_check_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/deviceCheckConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def recaptcha_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified recaptcha_config string.""" + return "projects/{project}/apps/{app}/recaptchaConfig".format(project=project, app=app, ) + + @staticmethod + def parse_recaptcha_config_path(path: str) -> Dict[str,str]: + """Parses a recaptcha_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/recaptchaConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def safety_net_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified safety_net_config string.""" + return "projects/{project}/apps/{app}/safetyNetConfig".format(project=project, app=app, ) + + @staticmethod + def parse_safety_net_config_path(path: str) -> Dict[str,str]: + """Parses a safety_net_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/safetyNetConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/services/{service}".format(project=project, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ConfigServiceTransport]): 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, ConfigServiceTransport): + # transport is a ConfigServiceTransport 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, + ) + + def get_app_attest_config(self, + request: configuration.GetAppAttestConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Gets the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + for the specified app. + + Args: + request (google.firebase.appcheck_v1beta.types.GetAppAttestConfigRequest): + The request object. Request message for the + [GetAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.GetAppAttestConfig] + method. + name (str): + Required. The relative resource name of the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + + 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.firebase.appcheck_v1beta.types.AppAttestConfig: + An app's App Attest configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetAppAttestConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetAppAttestConfigRequest): + request = configuration.GetAppAttestConfigRequest(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_app_attest_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 batch_get_app_attest_configs(self, + request: configuration.BatchGetAppAttestConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetAppAttestConfigsResponse: + r"""Gets the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + for the specified list of apps atomically. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetAppAttestConfigsRequest): + The request object. Request message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + parent (str): + Required. The parent project name shared by all + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetAppAttestConfigsResponse: + Response message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + 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 configuration.BatchGetAppAttestConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetAppAttestConfigsRequest): + request = configuration.BatchGetAppAttestConfigsRequest(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.batch_get_app_attest_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, + ) + + # Done; return the response. + return response + + def update_app_attest_config(self, + request: configuration.UpdateAppAttestConfigRequest = None, + *, + app_attest_config: configuration.AppAttestConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Updates the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange AppAttest tokens for App Check tokens. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateAppAttestConfigRequest): + The request object. Request message for the + [UpdateAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateAppAttestConfig] + method. + app_attest_config (google.firebase.appcheck_v1beta.types.AppAttestConfig): + Required. The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + to update. + + The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + + This corresponds to the ``app_attest_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + Gets to update. Example: ``token_ttl``. + + 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.firebase.appcheck_v1beta.types.AppAttestConfig: + An app's App Attest configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([app_attest_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 configuration.UpdateAppAttestConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateAppAttestConfigRequest): + request = configuration.UpdateAppAttestConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app_attest_config is not None: + request.app_attest_config = app_attest_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_app_attest_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app_attest_config.name", request.app_attest_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_device_check_config(self, + request: configuration.GetDeviceCheckConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Gets the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + for the specified app. + + For security reasons, the + [``private_key``][google.firebase.appcheck.v1beta.DeviceCheckConfig.private_key] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.GetDeviceCheckConfigRequest): + The request object. Request message for the + [GetDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.GetDeviceCheckConfig] + method. + name (str): + Required. The relative resource name of the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + + 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.firebase.appcheck_v1beta.types.DeviceCheckConfig: + An app's DeviceCheck configuration object. This configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by + DeviceCheck. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetDeviceCheckConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetDeviceCheckConfigRequest): + request = configuration.GetDeviceCheckConfigRequest(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_device_check_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 batch_get_device_check_configs(self, + request: configuration.BatchGetDeviceCheckConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetDeviceCheckConfigsResponse: + r"""Gets the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + for the specified list of apps atomically. + + For security reasons, the + [``private_key``][google.firebase.appcheck.v1beta.DeviceCheckConfig.private_key] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetDeviceCheckConfigsRequest): + The request object. Request message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + parent (str): + Required. The parent project name shared by all + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetDeviceCheckConfigsResponse: + Response message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + 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 configuration.BatchGetDeviceCheckConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetDeviceCheckConfigsRequest): + request = configuration.BatchGetDeviceCheckConfigsRequest(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.batch_get_device_check_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, + ) + + # Done; return the response. + return response + + def update_device_check_config(self, + request: configuration.UpdateDeviceCheckConfigRequest = None, + *, + device_check_config: configuration.DeviceCheckConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Updates the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange DeviceCheck tokens for App Check tokens. + + For security reasons, the + [``private_key``][google.firebase.appcheck.v1beta.DeviceCheckConfig.private_key] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateDeviceCheckConfigRequest): + The request object. Request message for the + [UpdateDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateDeviceCheckConfig] + method. + device_check_config (google.firebase.appcheck_v1beta.types.DeviceCheckConfig): + Required. The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + to update. + + The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + + This corresponds to the ``device_check_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + Gets to update. Example: ``key_id,private_key``. + + 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.firebase.appcheck_v1beta.types.DeviceCheckConfig: + An app's DeviceCheck configuration object. This configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by + DeviceCheck. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([device_check_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 configuration.UpdateDeviceCheckConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateDeviceCheckConfigRequest): + request = configuration.UpdateDeviceCheckConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if device_check_config is not None: + request.device_check_config = device_check_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_device_check_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("device_check_config.name", request.device_check_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_recaptcha_config(self, + request: configuration.GetRecaptchaConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Gets the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + for the specified app. + + For security reasons, the + [``site_secret``][google.firebase.appcheck.v1beta.RecaptchaConfig.site_secret] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.GetRecaptchaConfigRequest): + The request object. Request message for the + [GetRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.GetRecaptchaConfig] + method. + name (str): + Required. The relative resource name of the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + + 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.firebase.appcheck_v1beta.types.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by + reCAPTCHA v3. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetRecaptchaConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetRecaptchaConfigRequest): + request = configuration.GetRecaptchaConfigRequest(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_recaptcha_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 batch_get_recaptcha_configs(self, + request: configuration.BatchGetRecaptchaConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetRecaptchaConfigsResponse: + r"""Gets the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + for the specified list of apps atomically. + + For security reasons, the + [``site_secret``][google.firebase.appcheck.v1beta.RecaptchaConfig.site_secret] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetRecaptchaConfigsRequest): + The request object. Request message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + parent (str): + Required. The parent project name shared by all + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetRecaptchaConfigsResponse: + Response message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + 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 configuration.BatchGetRecaptchaConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetRecaptchaConfigsRequest): + request = configuration.BatchGetRecaptchaConfigsRequest(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.batch_get_recaptcha_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, + ) + + # Done; return the response. + return response + + def update_recaptcha_config(self, + request: configuration.UpdateRecaptchaConfigRequest = None, + *, + recaptcha_config: configuration.RecaptchaConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Updates the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange reCAPTCHA tokens for App Check tokens. + + For security reasons, the + [``site_secret``][google.firebase.appcheck.v1beta.RecaptchaConfig.site_secret] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateRecaptchaConfigRequest): + The request object. Request message for the + [UpdateRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateRecaptchaConfig] + method. + recaptcha_config (google.firebase.appcheck_v1beta.types.RecaptchaConfig): + Required. The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. + + The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + + This corresponds to the ``recaptcha_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. Example: ``site_secret``. + + 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.firebase.appcheck_v1beta.types.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by + reCAPTCHA v3. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([recaptcha_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 configuration.UpdateRecaptchaConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateRecaptchaConfigRequest): + request = configuration.UpdateRecaptchaConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if recaptcha_config is not None: + request.recaptcha_config = recaptcha_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_recaptcha_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("recaptcha_config.name", request.recaptcha_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_safety_net_config(self, + request: configuration.GetSafetyNetConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Gets the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + for the specified app. + + Args: + request (google.firebase.appcheck_v1beta.types.GetSafetyNetConfigRequest): + The request object. Request message for the + [GetSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.GetSafetyNetConfig] + method. + name (str): + Required. The relative resource name of the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + + 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.firebase.appcheck_v1beta.types.SafetyNetConfig: + An app's SafetyNet configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase + Console or programmatically via the [Firebase + Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.androidApps.sha/create). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetSafetyNetConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetSafetyNetConfigRequest): + request = configuration.GetSafetyNetConfigRequest(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_safety_net_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 batch_get_safety_net_configs(self, + request: configuration.BatchGetSafetyNetConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetSafetyNetConfigsResponse: + r"""Gets the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + for the specified list of apps atomically. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetSafetyNetConfigsRequest): + The request object. Request message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + parent (str): + Required. The parent project name shared by all + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetSafetyNetConfigsResponse: + Response message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + 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 configuration.BatchGetSafetyNetConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetSafetyNetConfigsRequest): + request = configuration.BatchGetSafetyNetConfigsRequest(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.batch_get_safety_net_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, + ) + + # Done; return the response. + return response + + def update_safety_net_config(self, + request: configuration.UpdateSafetyNetConfigRequest = None, + *, + safety_net_config: configuration.SafetyNetConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Updates the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange SafetyNet tokens for App Check tokens. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateSafetyNetConfigRequest): + The request object. Request message for the + [UpdateSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateSafetyNetConfig] + method. + safety_net_config (google.firebase.appcheck_v1beta.types.SafetyNetConfig): + Required. The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + to update. + + The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + + This corresponds to the ``safety_net_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + Gets to update. Example: ``token_ttl``. + + 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.firebase.appcheck_v1beta.types.SafetyNetConfig: + An app's SafetyNet configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase + Console or programmatically via the [Firebase + Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.androidApps.sha/create). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([safety_net_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 configuration.UpdateSafetyNetConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateSafetyNetConfigRequest): + request = configuration.UpdateSafetyNetConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if safety_net_config is not None: + request.safety_net_config = safety_net_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_safety_net_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("safety_net_config.name", request.safety_net_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_debug_token(self, + request: configuration.GetDebugTokenRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Gets the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]. + + For security reasons, the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.GetDebugTokenRequest): + The request object. Request message for the + [GetDebugToken][google.firebase.appcheck.v1beta.ConfigService.GetDebugToken] + method. + name (str): + Required. The relative resource name of the debug token, + in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.DebugToken: + A *debug token* is a secret used during the development or integration + testing of an app. It essentially allows the + development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetDebugTokenRequest): + request = configuration.GetDebugTokenRequest(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_debug_token] + + # Certain fields should be 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_debug_tokens(self, + request: configuration.ListDebugTokensRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDebugTokensPager: + r"""Lists all + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s for + the specified app. + + For security reasons, the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.ListDebugTokensRequest): + The request object. Request message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + parent (str): + Required. The relative resource name of the parent app + for which to list each associated + [DebugToken][google.firebase.appcheck.v1beta.DebugToken], + in the format: + + :: + + projects/{project_number}/apps/{app_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.services.config_service.pagers.ListDebugTokensPager: + Response message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + 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 configuration.ListDebugTokensRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.ListDebugTokensRequest): + request = configuration.ListDebugTokensRequest(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_debug_tokens] + + # Certain fields should be provided 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.ListDebugTokensPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_debug_token(self, + request: configuration.CreateDebugTokenRequest = None, + *, + parent: str = None, + debug_token: configuration.DebugToken = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Creates a new + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] for the + specified app. + + For security reasons, after the creation operation completes, + the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field cannot be updated or retrieved, but you can revoke the + debug token using + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken]. + + Each app can have a maximum of 20 debug tokens. + + Args: + request (google.firebase.appcheck_v1beta.types.CreateDebugTokenRequest): + The request object. Request message for the + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken] + method. + parent (str): + Required. The relative resource name of the parent app + in which the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will be created, in the format: + + :: + + projects/{project_number}/apps/{app_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to create. + + For security reasons, after creation, the ``token`` + field of the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will never be populated in any response. + + This corresponds to the ``debug_token`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.DebugToken: + A *debug token* is a secret used during the development or integration + testing of an app. It essentially allows the + development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, debug_token]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a configuration.CreateDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.CreateDebugTokenRequest): + request = configuration.CreateDebugTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if debug_token is not None: + request.debug_token = debug_token + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_debug_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_debug_token(self, + request: configuration.UpdateDebugTokenRequest = None, + *, + debug_token: configuration.DebugToken = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Updates the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]. + + For security reasons, the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field cannot be updated, nor will it be populated in the + response, but you can revoke the debug token using + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken]. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateDebugTokenRequest): + The request object. Request message for the + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + method. + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to update. + + The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]'s + ``name`` field is used to identify the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + + This corresponds to the ``debug_token`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to update. Example: ``display_name``. + + 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.firebase.appcheck_v1beta.types.DebugToken: + A *debug token* is a secret used during the development or integration + testing of an app. It essentially allows the + development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([debug_token, 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 configuration.UpdateDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateDebugTokenRequest): + request = configuration.UpdateDebugTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if debug_token is not None: + request.debug_token = debug_token + 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_debug_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("debug_token.name", request.debug_token.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_debug_token(self, + request: configuration.DeleteDebugTokenRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]. + + A deleted debug token cannot be used to exchange for an App + Check token. Use this method when you suspect the secret + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + has been compromised or when you no longer need the debug token. + + Args: + request (google.firebase.appcheck_v1beta.types.DeleteDebugTokenRequest): + The request object. Request message for the + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + method. + name (str): + Required. The relative resource name of the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to delete, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a configuration.DeleteDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.DeleteDebugTokenRequest): + request = configuration.DeleteDebugTokenRequest(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_debug_token] + + # Certain fields should be 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_service(self, + request: configuration.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Gets the [Service][google.firebase.appcheck.v1beta.Service] + configuration for the specified service name. + + Args: + request (google.firebase.appcheck_v1beta.types.GetServiceRequest): + The request object. Request message for the + [GetService][google.firebase.appcheck.v1beta.ConfigService.GetService] + method. + name (str): + Required. The relative resource name of the + [Service][google.firebase.appcheck.v1beta.Service] to + retrieve, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase + Realtime Database) + + 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.firebase.appcheck_v1beta.types.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetServiceRequest): + request = configuration.GetServiceRequest(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_service] + + # Certain fields should be 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_services(self, + request: configuration.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""Lists all [Service][google.firebase.appcheck.v1beta.Service] + configurations for the specified project. + + Only [Service][google.firebase.appcheck.v1beta.Service]s which + were explicitly configured using + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + or + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + will be returned. + + Args: + request (google.firebase.appcheck_v1beta.types.ListServicesRequest): + The request object. Request message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + parent (str): + Required. The relative resource name of the parent + project for which to list each associated + [Service][google.firebase.appcheck.v1beta.Service], in + the format: + + :: + + projects/{project_number} + + 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.firebase.appcheck_v1beta.services.config_service.pagers.ListServicesPager: + Response message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + 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 configuration.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.ListServicesRequest): + request = configuration.ListServicesRequest(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_services] + + # Certain fields should be provided 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.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: configuration.UpdateServiceRequest = None, + *, + service: configuration.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Updates the specified + [Service][google.firebase.appcheck.v1beta.Service] + configuration. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateServiceRequest): + The request object. Request message for the + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + method as well as an individual update message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + service (google.firebase.appcheck_v1beta.types.Service): + Required. The + [Service][google.firebase.appcheck.v1beta.Service] to + update. + + The [Service][google.firebase.appcheck.v1beta.Service]'s + ``name`` field is used to identify the + [Service][google.firebase.appcheck.v1beta.Service] to be + updated, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase + Realtime Database) + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the [Service][google.firebase.appcheck.v1beta.Service] + to update. Example: ``enforcement_mode``. + + 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.firebase.appcheck_v1beta.types.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 configuration.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateServiceRequest): + request = configuration.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_services(self, + request: configuration.BatchUpdateServicesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchUpdateServicesResponse: + r"""Updates the specified + [Service][google.firebase.appcheck.v1beta.Service] + configurations atomically. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchUpdateServicesRequest): + The request object. Request message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + 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.firebase.appcheck_v1beta.types.BatchUpdateServicesResponse: + Response message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a configuration.BatchUpdateServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchUpdateServicesRequest): + request = configuration.BatchUpdateServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_services] + + # Certain fields should be provided 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-firebase-appcheck", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConfigServiceClient", +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/pagers.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/pagers.py new file mode 100644 index 000000000..35893403e --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/pagers.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.firebase.appcheck_v1beta.types import configuration + + +class ListDebugTokensPager: + """A pager for iterating through ``list_debug_tokens`` requests. + + This class thinly wraps an initial + :class:`google.firebase.appcheck_v1beta.types.ListDebugTokensResponse` object, and + provides an ``__iter__`` method to iterate through its + ``debug_tokens`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDebugTokens`` requests and continue to iterate + through the ``debug_tokens`` field on the + corresponding responses. + + All the usual :class:`google.firebase.appcheck_v1beta.types.ListDebugTokensResponse` + 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[..., configuration.ListDebugTokensResponse], + request: configuration.ListDebugTokensRequest, + response: configuration.ListDebugTokensResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.firebase.appcheck_v1beta.types.ListDebugTokensRequest): + The initial request object. + response (google.firebase.appcheck_v1beta.types.ListDebugTokensResponse): + 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 = configuration.ListDebugTokensRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[configuration.ListDebugTokensResponse]: + 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[configuration.DebugToken]: + for page in self.pages: + yield from page.debug_tokens + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.firebase.appcheck_v1beta.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.firebase.appcheck_v1beta.types.ListServicesResponse` + 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[..., configuration.ListServicesResponse], + request: configuration.ListServicesRequest, + response: configuration.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.firebase.appcheck_v1beta.types.ListServicesRequest): + The initial request object. + response (google.firebase.appcheck_v1beta.types.ListServicesResponse): + 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 = configuration.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[configuration.ListServicesResponse]: + 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[configuration.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/__init__.py new file mode 100644 index 000000000..390d54e23 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ConfigServiceTransport +from .rest import ConfigServiceRestTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceTransport]] +_transport_registry['rest'] = ConfigServiceRestTransport + +__all__ = ( + 'ConfigServiceTransport', + 'ConfigServiceRestTransport', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/base.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/base.py new file mode 100644 index 000000000..dc6c1c2b8 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/base.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from requests import __version__ as requests_version + +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.firebase.appcheck_v1beta.types import configuration +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-firebase-appcheck', + ).version, + grpc_version=None, + rest_version=requests_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 ConfigServiceTransport(abc.ABC): + """Abstract transport class for ConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', + ) + + DEFAULT_HOST: str = 'firebaseappcheck.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_app_attest_config: gapic_v1.method.wrap_method( + self.get_app_attest_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_app_attest_configs: gapic_v1.method.wrap_method( + self.batch_get_app_attest_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_app_attest_config: gapic_v1.method.wrap_method( + self.update_app_attest_config, + default_timeout=None, + client_info=client_info, + ), + self.get_device_check_config: gapic_v1.method.wrap_method( + self.get_device_check_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_device_check_configs: gapic_v1.method.wrap_method( + self.batch_get_device_check_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_device_check_config: gapic_v1.method.wrap_method( + self.update_device_check_config, + default_timeout=None, + client_info=client_info, + ), + self.get_recaptcha_config: gapic_v1.method.wrap_method( + self.get_recaptcha_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_recaptcha_configs: gapic_v1.method.wrap_method( + self.batch_get_recaptcha_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_recaptcha_config: gapic_v1.method.wrap_method( + self.update_recaptcha_config, + default_timeout=None, + client_info=client_info, + ), + self.get_safety_net_config: gapic_v1.method.wrap_method( + self.get_safety_net_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_safety_net_configs: gapic_v1.method.wrap_method( + self.batch_get_safety_net_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_safety_net_config: gapic_v1.method.wrap_method( + self.update_safety_net_config, + default_timeout=None, + client_info=client_info, + ), + self.get_debug_token: gapic_v1.method.wrap_method( + self.get_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.list_debug_tokens: gapic_v1.method.wrap_method( + self.list_debug_tokens, + default_timeout=None, + client_info=client_info, + ), + self.create_debug_token: gapic_v1.method.wrap_method( + self.create_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.update_debug_token: gapic_v1.method.wrap_method( + self.update_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.delete_debug_token: gapic_v1.method.wrap_method( + self.delete_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_services: gapic_v1.method.wrap_method( + self.batch_update_services, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_app_attest_config(self) -> Callable[ + [configuration.GetAppAttestConfigRequest], + Union[ + configuration.AppAttestConfig, + Awaitable[configuration.AppAttestConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_app_attest_configs(self) -> Callable[ + [configuration.BatchGetAppAttestConfigsRequest], + Union[ + configuration.BatchGetAppAttestConfigsResponse, + Awaitable[configuration.BatchGetAppAttestConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_app_attest_config(self) -> Callable[ + [configuration.UpdateAppAttestConfigRequest], + Union[ + configuration.AppAttestConfig, + Awaitable[configuration.AppAttestConfig] + ]]: + raise NotImplementedError() + + @property + def get_device_check_config(self) -> Callable[ + [configuration.GetDeviceCheckConfigRequest], + Union[ + configuration.DeviceCheckConfig, + Awaitable[configuration.DeviceCheckConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_device_check_configs(self) -> Callable[ + [configuration.BatchGetDeviceCheckConfigsRequest], + Union[ + configuration.BatchGetDeviceCheckConfigsResponse, + Awaitable[configuration.BatchGetDeviceCheckConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_device_check_config(self) -> Callable[ + [configuration.UpdateDeviceCheckConfigRequest], + Union[ + configuration.DeviceCheckConfig, + Awaitable[configuration.DeviceCheckConfig] + ]]: + raise NotImplementedError() + + @property + def get_recaptcha_config(self) -> Callable[ + [configuration.GetRecaptchaConfigRequest], + Union[ + configuration.RecaptchaConfig, + Awaitable[configuration.RecaptchaConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_recaptcha_configs(self) -> Callable[ + [configuration.BatchGetRecaptchaConfigsRequest], + Union[ + configuration.BatchGetRecaptchaConfigsResponse, + Awaitable[configuration.BatchGetRecaptchaConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_recaptcha_config(self) -> Callable[ + [configuration.UpdateRecaptchaConfigRequest], + Union[ + configuration.RecaptchaConfig, + Awaitable[configuration.RecaptchaConfig] + ]]: + raise NotImplementedError() + + @property + def get_safety_net_config(self) -> Callable[ + [configuration.GetSafetyNetConfigRequest], + Union[ + configuration.SafetyNetConfig, + Awaitable[configuration.SafetyNetConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_safety_net_configs(self) -> Callable[ + [configuration.BatchGetSafetyNetConfigsRequest], + Union[ + configuration.BatchGetSafetyNetConfigsResponse, + Awaitable[configuration.BatchGetSafetyNetConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_safety_net_config(self) -> Callable[ + [configuration.UpdateSafetyNetConfigRequest], + Union[ + configuration.SafetyNetConfig, + Awaitable[configuration.SafetyNetConfig] + ]]: + raise NotImplementedError() + + @property + def get_debug_token(self) -> Callable[ + [configuration.GetDebugTokenRequest], + Union[ + configuration.DebugToken, + Awaitable[configuration.DebugToken] + ]]: + raise NotImplementedError() + + @property + def list_debug_tokens(self) -> Callable[ + [configuration.ListDebugTokensRequest], + Union[ + configuration.ListDebugTokensResponse, + Awaitable[configuration.ListDebugTokensResponse] + ]]: + raise NotImplementedError() + + @property + def create_debug_token(self) -> Callable[ + [configuration.CreateDebugTokenRequest], + Union[ + configuration.DebugToken, + Awaitable[configuration.DebugToken] + ]]: + raise NotImplementedError() + + @property + def update_debug_token(self) -> Callable[ + [configuration.UpdateDebugTokenRequest], + Union[ + configuration.DebugToken, + Awaitable[configuration.DebugToken] + ]]: + raise NotImplementedError() + + @property + def delete_debug_token(self) -> Callable[ + [configuration.DeleteDebugTokenRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [configuration.GetServiceRequest], + Union[ + configuration.Service, + Awaitable[configuration.Service] + ]]: + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [configuration.ListServicesRequest], + Union[ + configuration.ListServicesResponse, + Awaitable[configuration.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [configuration.UpdateServiceRequest], + Union[ + configuration.Service, + Awaitable[configuration.Service] + ]]: + raise NotImplementedError() + + @property + def batch_update_services(self) -> Callable[ + [configuration.BatchUpdateServicesRequest], + Union[ + configuration.BatchUpdateServicesResponse, + Awaitable[configuration.BatchUpdateServicesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ConfigServiceTransport', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/rest.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/rest.py new file mode 100644 index 000000000..89b48a6c0 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/config_service/transports/rest.py @@ -0,0 +1,1392 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.firebase.appcheck_v1beta.types import configuration +from google.protobuf import empty_pb2 # type: ignore + +from .base import ConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ConfigServiceRestTransport(ConfigServiceTransport): + """REST backend transport for ConfigService. + + Manages configuration parameters used by the + [TokenExchangeService][google.firebase.appcheck.v1beta.TokenExchangeService] + and enforcement settings for Firebase services protected by App + Check. + + 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 JSON representations of protocol buffers over HTTP/1.1 + """ + def __init__(self, *, + host: str = 'firebaseappcheck.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = 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. + + 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. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + self._session = AuthorizedSession(self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._prep_wrapped_messages(client_info) + + def get_app_attest_config(self, + request: configuration.GetAppAttestConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Call the get app attest config method over HTTP. + + Args: + request (~.configuration.GetAppAttestConfigRequest): + The request object. Request message for the + [GetAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.GetAppAttestConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.AppAttestConfig: + An app's App Attest configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/appAttestConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.AppAttestConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_app_attest_configs(self, + request: configuration.BatchGetAppAttestConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetAppAttestConfigsResponse: + r"""Call the batch get app attest + configs method over HTTP. + + Args: + request (~.configuration.BatchGetAppAttestConfigsRequest): + The request object. Request message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetAppAttestConfigsResponse: + Response message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/appAttestConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetAppAttestConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_app_attest_config(self, + request: configuration.UpdateAppAttestConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Call the update app attest config method over HTTP. + + Args: + request (~.configuration.UpdateAppAttestConfigRequest): + The request object. Request message for the + [UpdateAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateAppAttestConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.AppAttestConfig: + An app's App Attest configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # Jsonify the request body + body = configuration.AppAttestConfig.to_json( + request.app_attest_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app_attest_config.name=projects/*/apps/*/appAttestConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.AppAttestConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_device_check_config(self, + request: configuration.GetDeviceCheckConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Call the get device check config method over HTTP. + + Args: + request (~.configuration.GetDeviceCheckConfigRequest): + The request object. Request message for the + [GetDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.GetDeviceCheckConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DeviceCheckConfig: + An app's DeviceCheck configuration object. This + configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by DeviceCheck. + It also controls certain properties of the returned [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/deviceCheckConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DeviceCheckConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_device_check_configs(self, + request: configuration.BatchGetDeviceCheckConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetDeviceCheckConfigsResponse: + r"""Call the batch get device check + configs method over HTTP. + + Args: + request (~.configuration.BatchGetDeviceCheckConfigsRequest): + The request object. Request message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetDeviceCheckConfigsResponse: + Response message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/deviceCheckConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetDeviceCheckConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_device_check_config(self, + request: configuration.UpdateDeviceCheckConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Call the update device check + config method over HTTP. + + Args: + request (~.configuration.UpdateDeviceCheckConfigRequest): + The request object. Request message for the + [UpdateDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateDeviceCheckConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DeviceCheckConfig: + An app's DeviceCheck configuration object. This + configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by DeviceCheck. + It also controls certain properties of the returned [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # Jsonify the request body + body = configuration.DeviceCheckConfig.to_json( + request.device_check_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{device_check_config.name=projects/*/apps/*/deviceCheckConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DeviceCheckConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_recaptcha_config(self, + request: configuration.GetRecaptchaConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Call the get recaptcha config method over HTTP. + + Args: + request (~.configuration.GetRecaptchaConfigRequest): + The request object. Request message for the + [GetRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.GetRecaptchaConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This + configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by reCAPTCHA + v3. It also controls certain properties of the returned + [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/recaptchaConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.RecaptchaConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_recaptcha_configs(self, + request: configuration.BatchGetRecaptchaConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetRecaptchaConfigsResponse: + r"""Call the batch get recaptcha + configs method over HTTP. + + Args: + request (~.configuration.BatchGetRecaptchaConfigsRequest): + The request object. Request message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetRecaptchaConfigsResponse: + Response message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/recaptchaConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetRecaptchaConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_recaptcha_config(self, + request: configuration.UpdateRecaptchaConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Call the update recaptcha config method over HTTP. + + Args: + request (~.configuration.UpdateRecaptchaConfigRequest): + The request object. Request message for the + [UpdateRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateRecaptchaConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This + configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by reCAPTCHA + v3. It also controls certain properties of the returned + [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + + # Jsonify the request body + body = configuration.RecaptchaConfig.to_json( + request.recaptcha_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{recaptcha_config.name=projects/*/apps/*/recaptchaConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.RecaptchaConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_safety_net_config(self, + request: configuration.GetSafetyNetConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Call the get safety net config method over HTTP. + + Args: + request (~.configuration.GetSafetyNetConfigRequest): + The request object. Request message for the + [GetSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.GetSafetyNetConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.SafetyNetConfig: + An app's SafetyNet configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/safetyNetConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.SafetyNetConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_safety_net_configs(self, + request: configuration.BatchGetSafetyNetConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetSafetyNetConfigsResponse: + r"""Call the batch get safety net + configs method over HTTP. + + Args: + request (~.configuration.BatchGetSafetyNetConfigsRequest): + The request object. Request message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetSafetyNetConfigsResponse: + Response message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/safetyNetConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetSafetyNetConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_safety_net_config(self, + request: configuration.UpdateSafetyNetConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Call the update safety net config method over HTTP. + + Args: + request (~.configuration.UpdateSafetyNetConfigRequest): + The request object. Request message for the + [UpdateSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateSafetyNetConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.SafetyNetConfig: + An app's SafetyNet configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + """ + + # Jsonify the request body + body = configuration.SafetyNetConfig.to_json( + request.safety_net_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{safety_net_config.name=projects/*/apps/*/safetyNetConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.SafetyNetConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_debug_token(self, + request: configuration.GetDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Call the get debug token method over HTTP. + + Args: + request (~.configuration.GetDebugTokenRequest): + The request object. Request message for the + [GetDebugToken][google.firebase.appcheck.v1beta.ConfigService.GetDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DebugToken: + A *debug token* is a secret used during the development + or integration testing of an app. It essentially allows + the development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/debugTokens/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DebugToken.from_json( + response.content, + ignore_unknown_fields=True + ) + + def list_debug_tokens(self, + request: configuration.ListDebugTokensRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.ListDebugTokensResponse: + r"""Call the list debug tokens method over HTTP. + + Args: + request (~.configuration.ListDebugTokensRequest): + The request object. Request message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.ListDebugTokensResponse: + Response message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*/apps/*}/debugTokens'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['pageSize'] = request.page_size + query_params['pageToken'] = request.page_token + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.ListDebugTokensResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def create_debug_token(self, + request: configuration.CreateDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Call the create debug token method over HTTP. + + Args: + request (~.configuration.CreateDebugTokenRequest): + The request object. Request message for the + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DebugToken: + A *debug token* is a secret used during the development + or integration testing of an app. It essentially allows + the development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + + # Jsonify the request body + body = configuration.DebugToken.to_json( + request.debug_token, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*/apps/*}/debugTokens'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DebugToken.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_debug_token(self, + request: configuration.UpdateDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Call the update debug token method over HTTP. + + Args: + request (~.configuration.UpdateDebugTokenRequest): + The request object. Request message for the + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DebugToken: + A *debug token* is a secret used during the development + or integration testing of an app. It essentially allows + the development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + + # Jsonify the request body + body = configuration.DebugToken.to_json( + request.debug_token, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{debug_token.name=projects/*/apps/*/debugTokens/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DebugToken.from_json( + response.content, + ignore_unknown_fields=True + ) + + def delete_debug_token(self, + request: configuration.DeleteDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> empty_pb2.Empty: + r"""Call the delete debug token method over HTTP. + + Args: + request (~.configuration.DeleteDebugTokenRequest): + The request object. Request message for the + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/debugTokens/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.delete( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + def get_service(self, + request: configuration.GetServiceRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Call the get service method over HTTP. + + Args: + request (~.configuration.GetServiceRequest): + The request object. Request message for the + [GetService][google.firebase.appcheck.v1beta.ConfigService.GetService] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/services/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.Service.from_json( + response.content, + ignore_unknown_fields=True + ) + + def list_services(self, + request: configuration.ListServicesRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.configuration.ListServicesRequest): + The request object. Request message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.ListServicesResponse: + Response message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/services'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['pageSize'] = request.page_size + query_params['pageToken'] = request.page_token + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.ListServicesResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_service(self, + request: configuration.UpdateServiceRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Call the update service method over HTTP. + + Args: + request (~.configuration.UpdateServiceRequest): + The request object. Request message for the + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + method as well as an individual update message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + + # Jsonify the request body + body = configuration.Service.to_json( + request.service, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{service.name=projects/*/services/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.Service.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_update_services(self, + request: configuration.BatchUpdateServicesRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchUpdateServicesResponse: + r"""Call the batch update services method over HTTP. + + Args: + request (~.configuration.BatchUpdateServicesRequest): + The request object. Request message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchUpdateServicesResponse: + Response message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + """ + + # Jsonify the request body + body = configuration.BatchUpdateServicesRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/services:batchUpdate'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['parent'] = request.parent + query_params['requests'] = request.requests + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchUpdateServicesResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + +__all__ = ( + 'ConfigServiceRestTransport', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/__init__.py new file mode 100644 index 000000000..41feb8785 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/__init__.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TokenExchangeServiceClient + +__all__ = ( + 'TokenExchangeServiceClient', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/client.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/client.py new file mode 100644 index 000000000..5e78359ea --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/client.py @@ -0,0 +1,917 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.firebase.appcheck_v1beta.types import token_exchange_service +from google.protobuf import duration_pb2 # type: ignore +from .transports.base import TokenExchangeServiceTransport, DEFAULT_CLIENT_INFO +from .transports.rest import TokenExchangeServiceRestTransport + + +class TokenExchangeServiceClientMeta(type): + """Metaclass for the TokenExchangeService 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[TokenExchangeServiceTransport]] + _transport_registry["rest"] = TokenExchangeServiceRestTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TokenExchangeServiceTransport]: + """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 TokenExchangeServiceClient(metaclass=TokenExchangeServiceClientMeta): + """A service to validate certification material issued to apps by app + or device attestation providers, and exchange them for *App Check + tokens* (see + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]), + used to access Firebase services protected by App Check. + """ + + @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 = "firebaseappcheck.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: + TokenExchangeServiceClient: 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: + TokenExchangeServiceClient: 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) -> TokenExchangeServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TokenExchangeServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def public_jwk_set_path() -> str: + """Returns a fully-qualified public_jwk_set string.""" + return "jwks".format() + + @staticmethod + def parse_public_jwk_set_path(path: str) -> Dict[str,str]: + """Parses a public_jwk_set path into its component segments.""" + m = re.match(r"^jwks$", 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, TokenExchangeServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the token exchange service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TokenExchangeServiceTransport]): 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, TokenExchangeServiceTransport): + # transport is a TokenExchangeServiceTransport 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, + ) + + def get_public_jwk_set(self, + request: token_exchange_service.GetPublicJwkSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.PublicJwkSet: + r"""Returns a public JWK set as specified by `RFC + 7517 `__ that can be used + to verify App Check tokens. Exactly one of the public keys in + the returned set will successfully validate any App Check token + that is currently valid. + + Args: + request (google.firebase.appcheck_v1beta.types.GetPublicJwkSetRequest): + The request object. Request message for the + [GetPublicJwkSet][] method. + name (str): + Required. The relative resource name to the public JWK + set. Must always be exactly the string ``jwks``. + + 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.firebase.appcheck_v1beta.types.PublicJwkSet: + The currently active set of public keys that can be used to verify App Check + tokens. + + This object is a JWK set as specified by [section 5 + of RFC + 7517](\ https://tools.ietf.org/html/rfc7517#section-5). + + For security, the response **must not** be cached for + longer than one day. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 token_exchange_service.GetPublicJwkSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.GetPublicJwkSetRequest): + request = token_exchange_service.GetPublicJwkSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_public_jwk_set] + + # Certain fields should be 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 exchange_safety_net_token(self, + request: token_exchange_service.ExchangeSafetyNetTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a `SafetyNet + token `__. + If valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeSafetyNetTokenRequest): + The request object. Request message for the + [ExchangeSafetyNetToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeSafetyNetTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeSafetyNetTokenRequest): + request = token_exchange_service.ExchangeSafetyNetTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_safety_net_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_device_check_token(self, + request: token_exchange_service.ExchangeDeviceCheckTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Accepts a + ```device_token`` `__ + issued by DeviceCheck, and attempts to validate it with Apple. + If valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeDeviceCheckTokenRequest): + The request object. Request message for the + [ExchangeDeviceCheckToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeDeviceCheckTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeDeviceCheckTokenRequest): + request = token_exchange_service.ExchangeDeviceCheckTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_device_check_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_recaptcha_token(self, + request: token_exchange_service.ExchangeRecaptchaTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a `reCAPTCHA v3 response + token `__. If + valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeRecaptchaTokenRequest): + The request object. Request message for the + [ExchangeRecaptchaToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeRecaptchaTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeRecaptchaTokenRequest): + request = token_exchange_service.ExchangeRecaptchaTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_recaptcha_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_custom_token(self, + request: token_exchange_service.ExchangeCustomTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a custom token signed using your project's Admin SDK + service account credentials. If valid, returns an App Check + token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeCustomTokenRequest): + The request object. Request message for the + [ExchangeCustomToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeCustomTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeCustomTokenRequest): + request = token_exchange_service.ExchangeCustomTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_custom_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_debug_token(self, + request: token_exchange_service.ExchangeDebugTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a debug token secret that you have previously created + using + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken]. + If valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Note that a restrictive quota is enforced on this method to + prevent accidental exposure of the app to abuse. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeDebugTokenRequest): + The request object. Request message for the + [ExchangeDebugToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeDebugTokenRequest): + request = token_exchange_service.ExchangeDebugTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_debug_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_app_attest_challenge(self, + request: token_exchange_service.GenerateAppAttestChallengeRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AppAttestChallengeResponse: + r"""Initiates the App Attest flow by generating a + challenge which will be used as a type of nonce for this + attestation. + + Args: + request (google.firebase.appcheck_v1beta.types.GenerateAppAttestChallengeRequest): + The request object. Request message for + GenerateAppAttestChallenge + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.AppAttestChallengeResponse: + Response object for + GenerateAppAttestChallenge + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.GenerateAppAttestChallengeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.GenerateAppAttestChallengeRequest): + request = token_exchange_service.GenerateAppAttestChallengeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_app_attest_challenge] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_app_attest_attestation(self, + request: token_exchange_service.ExchangeAppAttestAttestationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.ExchangeAppAttestAttestationResponse: + r"""Accepts a AppAttest CBOR Attestation, and uses the + developer's preconfigured team and bundle IDs to verify + the token with Apple. Returns an Attestation Artifact + that can later be exchanged for an AttestationToken in + ExchangeAppAttestAssertion. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeAppAttestAttestationRequest): + The request object. Request message for + ExchangeAppAttestAttestation + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.ExchangeAppAttestAttestationResponse: + Response message for + ExchangeAppAttestAttestation and + ExchangeAppAttestDebugAttestation + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeAppAttestAttestationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeAppAttestAttestationRequest): + request = token_exchange_service.ExchangeAppAttestAttestationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_app_attest_attestation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_app_attest_assertion(self, + request: token_exchange_service.ExchangeAppAttestAssertionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Accepts a AppAttest Artifact and Assertion, and uses the + developer's preconfigured auth token to verify the token with + Apple. Returns an AttestationToken with the App ID as specified + by the ``app`` field included as attested claims. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeAppAttestAssertionRequest): + The request object. Request message for + ExchangeAppAttestAssertion + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeAppAttestAssertionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeAppAttestAssertionRequest): + request = token_exchange_service.ExchangeAppAttestAssertionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_app_attest_assertion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # 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-firebase-appcheck", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TokenExchangeServiceClient", +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/__init__.py new file mode 100644 index 000000000..d0f63506a --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TokenExchangeServiceTransport +from .rest import TokenExchangeServiceRestTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TokenExchangeServiceTransport]] +_transport_registry['rest'] = TokenExchangeServiceRestTransport + +__all__ = ( + 'TokenExchangeServiceTransport', + 'TokenExchangeServiceRestTransport', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/base.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/base.py new file mode 100644 index 000000000..3576d9456 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/base.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from requests import __version__ as requests_version + +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.firebase.appcheck_v1beta.types import token_exchange_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-firebase-appcheck', + ).version, + grpc_version=None, + rest_version=requests_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 TokenExchangeServiceTransport(abc.ABC): + """Abstract transport class for TokenExchangeService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', + ) + + DEFAULT_HOST: str = 'firebaseappcheck.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_public_jwk_set: gapic_v1.method.wrap_method( + self.get_public_jwk_set, + default_timeout=None, + client_info=client_info, + ), + self.exchange_safety_net_token: gapic_v1.method.wrap_method( + self.exchange_safety_net_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_device_check_token: gapic_v1.method.wrap_method( + self.exchange_device_check_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_recaptcha_token: gapic_v1.method.wrap_method( + self.exchange_recaptcha_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_custom_token: gapic_v1.method.wrap_method( + self.exchange_custom_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_debug_token: gapic_v1.method.wrap_method( + self.exchange_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.generate_app_attest_challenge: gapic_v1.method.wrap_method( + self.generate_app_attest_challenge, + default_timeout=None, + client_info=client_info, + ), + self.exchange_app_attest_attestation: gapic_v1.method.wrap_method( + self.exchange_app_attest_attestation, + default_timeout=None, + client_info=client_info, + ), + self.exchange_app_attest_assertion: gapic_v1.method.wrap_method( + self.exchange_app_attest_assertion, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_public_jwk_set(self) -> Callable[ + [token_exchange_service.GetPublicJwkSetRequest], + Union[ + token_exchange_service.PublicJwkSet, + Awaitable[token_exchange_service.PublicJwkSet] + ]]: + raise NotImplementedError() + + @property + def exchange_safety_net_token(self) -> Callable[ + [token_exchange_service.ExchangeSafetyNetTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_device_check_token(self) -> Callable[ + [token_exchange_service.ExchangeDeviceCheckTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_recaptcha_token(self) -> Callable[ + [token_exchange_service.ExchangeRecaptchaTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_custom_token(self) -> Callable[ + [token_exchange_service.ExchangeCustomTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_debug_token(self) -> Callable[ + [token_exchange_service.ExchangeDebugTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def generate_app_attest_challenge(self) -> Callable[ + [token_exchange_service.GenerateAppAttestChallengeRequest], + Union[ + token_exchange_service.AppAttestChallengeResponse, + Awaitable[token_exchange_service.AppAttestChallengeResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_app_attest_attestation(self) -> Callable[ + [token_exchange_service.ExchangeAppAttestAttestationRequest], + Union[ + token_exchange_service.ExchangeAppAttestAttestationResponse, + Awaitable[token_exchange_service.ExchangeAppAttestAttestationResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_app_attest_assertion(self) -> Callable[ + [token_exchange_service.ExchangeAppAttestAssertionRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TokenExchangeServiceTransport', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/rest.py b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/rest.py new file mode 100644 index 000000000..0251c0c31 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/rest.py @@ -0,0 +1,644 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.firebase.appcheck_v1beta.types import token_exchange_service + +from .base import TokenExchangeServiceTransport, DEFAULT_CLIENT_INFO + + +class TokenExchangeServiceRestTransport(TokenExchangeServiceTransport): + """REST backend transport for TokenExchangeService. + + A service to validate certification material issued to apps by app + or device attestation providers, and exchange them for *App Check + tokens* (see + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]), + used to access Firebase services protected by App Check. + + 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 JSON representations of protocol buffers over HTTP/1.1 + """ + def __init__(self, *, + host: str = 'firebaseappcheck.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = 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. + + 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. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + self._session = AuthorizedSession(self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._prep_wrapped_messages(client_info) + + def get_public_jwk_set(self, + request: token_exchange_service.GetPublicJwkSetRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.PublicJwkSet: + r"""Call the get public jwk set method over HTTP. + + Args: + request (~.token_exchange_service.GetPublicJwkSetRequest): + The request object. Request message for the [GetPublicJwkSet][] method. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.PublicJwkSet: + The currently active set of public keys that can be used + to verify App Check tokens. + + This object is a JWK set as specified by `section 5 of + RFC + 7517 `__. + + For security, the response **must not** be cached for + longer than one day. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=jwks}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.PublicJwkSet.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_safety_net_token(self, + request: token_exchange_service.ExchangeSafetyNetTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange safety net token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeSafetyNetTokenRequest): + The request object. Request message for the [ExchangeSafetyNetToken][] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeSafetyNetTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeSafetyNetToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['safetyNetToken'] = request.safety_net_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_device_check_token(self, + request: token_exchange_service.ExchangeDeviceCheckTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange device check + token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeDeviceCheckTokenRequest): + The request object. Request message for the [ExchangeDeviceCheckToken][] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeDeviceCheckTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeDeviceCheckToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['deviceToken'] = request.device_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_recaptcha_token(self, + request: token_exchange_service.ExchangeRecaptchaTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange recaptcha token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeRecaptchaTokenRequest): + The request object. Request message for the [ExchangeRecaptchaToken][] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeRecaptchaTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeRecaptchaToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['recaptchaToken'] = request.recaptcha_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_custom_token(self, + request: token_exchange_service.ExchangeCustomTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange custom token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeCustomTokenRequest): + The request object. Request message for the [ExchangeCustomToken][] method. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeCustomTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeCustomToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['customToken'] = request.custom_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_debug_token(self, + request: token_exchange_service.ExchangeDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange debug token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeDebugTokenRequest): + The request object. Request message for the [ExchangeDebugToken][] method. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeDebugTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeDebugToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['debugToken'] = request.debug_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def generate_app_attest_challenge(self, + request: token_exchange_service.GenerateAppAttestChallengeRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AppAttestChallengeResponse: + r"""Call the generate app attest + challenge method over HTTP. + + Args: + request (~.token_exchange_service.GenerateAppAttestChallengeRequest): + The request object. Request message for + GenerateAppAttestChallenge + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AppAttestChallengeResponse: + Response object for + GenerateAppAttestChallenge + + """ + + # Jsonify the request body + body = token_exchange_service.GenerateAppAttestChallengeRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:generateAppAttestChallenge'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AppAttestChallengeResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_app_attest_attestation(self, + request: token_exchange_service.ExchangeAppAttestAttestationRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.ExchangeAppAttestAttestationResponse: + r"""Call the exchange app attest + attestation method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeAppAttestAttestationRequest): + The request object. Request message for + ExchangeAppAttestAttestation + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.ExchangeAppAttestAttestationResponse: + Response message for + ExchangeAppAttestAttestation and + ExchangeAppAttestDebugAttestation + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeAppAttestAttestationRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeAppAttestAttestation'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['attestationStatement'] = request.attestation_statement + query_params['challenge'] = request.challenge + query_params['keyId'] = request.key_id + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.ExchangeAppAttestAttestationResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_app_attest_assertion(self, + request: token_exchange_service.ExchangeAppAttestAssertionRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange app attest + assertion method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeAppAttestAssertionRequest): + The request object. Request message for + ExchangeAppAttestAssertion + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeAppAttestAssertionRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeAppAttestAssertion'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['artifact'] = request.artifact + query_params['assertion'] = request.assertion + query_params['challenge'] = request.challenge + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + +__all__ = ( + 'TokenExchangeServiceRestTransport', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/types/__init__.py b/appcheck_gapic/google/firebase/appcheck_v1beta/types/__init__.py new file mode 100644 index 000000000..fce4e042a --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/types/__init__.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .configuration import ( + AppAttestConfig, + BatchGetAppAttestConfigsRequest, + BatchGetAppAttestConfigsResponse, + BatchGetDeviceCheckConfigsRequest, + BatchGetDeviceCheckConfigsResponse, + BatchGetRecaptchaConfigsRequest, + BatchGetRecaptchaConfigsResponse, + BatchGetSafetyNetConfigsRequest, + BatchGetSafetyNetConfigsResponse, + BatchUpdateServicesRequest, + BatchUpdateServicesResponse, + CreateDebugTokenRequest, + DebugToken, + DeleteDebugTokenRequest, + DeviceCheckConfig, + GetAppAttestConfigRequest, + GetDebugTokenRequest, + GetDeviceCheckConfigRequest, + GetRecaptchaConfigRequest, + GetSafetyNetConfigRequest, + GetServiceRequest, + ListDebugTokensRequest, + ListDebugTokensResponse, + ListServicesRequest, + ListServicesResponse, + RecaptchaConfig, + SafetyNetConfig, + Service, + UpdateAppAttestConfigRequest, + UpdateDebugTokenRequest, + UpdateDeviceCheckConfigRequest, + UpdateRecaptchaConfigRequest, + UpdateSafetyNetConfigRequest, + UpdateServiceRequest, +) +from .token_exchange_service import ( + AppAttestChallengeResponse, + AttestationTokenResponse, + ExchangeAppAttestAssertionRequest, + ExchangeAppAttestAttestationRequest, + ExchangeAppAttestAttestationResponse, + ExchangeCustomTokenRequest, + ExchangeDebugTokenRequest, + ExchangeDeviceCheckTokenRequest, + ExchangeRecaptchaTokenRequest, + ExchangeSafetyNetTokenRequest, + GenerateAppAttestChallengeRequest, + GetPublicJwkSetRequest, + PublicJwk, + PublicJwkSet, +) + +__all__ = ( + 'AppAttestConfig', + 'BatchGetAppAttestConfigsRequest', + 'BatchGetAppAttestConfigsResponse', + 'BatchGetDeviceCheckConfigsRequest', + 'BatchGetDeviceCheckConfigsResponse', + 'BatchGetRecaptchaConfigsRequest', + 'BatchGetRecaptchaConfigsResponse', + 'BatchGetSafetyNetConfigsRequest', + 'BatchGetSafetyNetConfigsResponse', + 'BatchUpdateServicesRequest', + 'BatchUpdateServicesResponse', + 'CreateDebugTokenRequest', + 'DebugToken', + 'DeleteDebugTokenRequest', + 'DeviceCheckConfig', + 'GetAppAttestConfigRequest', + 'GetDebugTokenRequest', + 'GetDeviceCheckConfigRequest', + 'GetRecaptchaConfigRequest', + 'GetSafetyNetConfigRequest', + 'GetServiceRequest', + 'ListDebugTokensRequest', + 'ListDebugTokensResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'RecaptchaConfig', + 'SafetyNetConfig', + 'Service', + 'UpdateAppAttestConfigRequest', + 'UpdateDebugTokenRequest', + 'UpdateDeviceCheckConfigRequest', + 'UpdateRecaptchaConfigRequest', + 'UpdateSafetyNetConfigRequest', + 'UpdateServiceRequest', + 'AppAttestChallengeResponse', + 'AttestationTokenResponse', + 'ExchangeAppAttestAssertionRequest', + 'ExchangeAppAttestAttestationRequest', + 'ExchangeAppAttestAttestationResponse', + 'ExchangeCustomTokenRequest', + 'ExchangeDebugTokenRequest', + 'ExchangeDeviceCheckTokenRequest', + 'ExchangeRecaptchaTokenRequest', + 'ExchangeSafetyNetTokenRequest', + 'GenerateAppAttestChallengeRequest', + 'GetPublicJwkSetRequest', + 'PublicJwk', + 'PublicJwkSet', +) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/types/config_service.py b/appcheck_gapic/google/firebase/appcheck_v1beta/types/config_service.py new file mode 100644 index 000000000..a4b1757d1 --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/types/config_service.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.firebase.appcheck.v1beta', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/types/configuration.py b/appcheck_gapic/google/firebase/appcheck_v1beta/types/configuration.py new file mode 100644 index 000000000..ae1904a4c --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/types/configuration.py @@ -0,0 +1,1277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.firebase.appcheck.v1beta', + manifest={ + 'AppAttestConfig', + 'GetAppAttestConfigRequest', + 'BatchGetAppAttestConfigsRequest', + 'BatchGetAppAttestConfigsResponse', + 'UpdateAppAttestConfigRequest', + 'DeviceCheckConfig', + 'GetDeviceCheckConfigRequest', + 'BatchGetDeviceCheckConfigsRequest', + 'BatchGetDeviceCheckConfigsResponse', + 'UpdateDeviceCheckConfigRequest', + 'RecaptchaConfig', + 'GetRecaptchaConfigRequest', + 'BatchGetRecaptchaConfigsRequest', + 'BatchGetRecaptchaConfigsResponse', + 'UpdateRecaptchaConfigRequest', + 'SafetyNetConfig', + 'GetSafetyNetConfigRequest', + 'BatchGetSafetyNetConfigsRequest', + 'BatchGetSafetyNetConfigsResponse', + 'UpdateSafetyNetConfigRequest', + 'DebugToken', + 'GetDebugTokenRequest', + 'ListDebugTokensRequest', + 'ListDebugTokensResponse', + 'CreateDebugTokenRequest', + 'UpdateDebugTokenRequest', + 'DeleteDebugTokenRequest', + 'Service', + 'GetServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'UpdateServiceRequest', + 'BatchUpdateServicesRequest', + 'BatchUpdateServicesResponse', + }, +) + + +class AppAttestConfig(proto.Message): + r"""An app's App Attest configuration object. This configuration + controls certain properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used as part of + the validation process. Please register it via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + Attributes: + name (str): + Required. The relative resource name of the App Attest + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from App Attest artifacts will + be valid. If unset, a default value of 1 hour is + assumed. Must be between 30 minutes and 7 days, + inclusive. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + token_ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class GetAppAttestConfigRequest(proto.Message): + r"""Request message for the + [GetAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.GetAppAttestConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetAppAttestConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + to retrieve, in the format + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetAppAttestConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.AppAttestConfig]): + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AppAttestConfig', + ) + + +class UpdateAppAttestConfigRequest(proto.Message): + r"""Request message for the + [UpdateAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateAppAttestConfig] + method. + + Attributes: + app_attest_config (google.firebase.appcheck_v1beta.types.AppAttestConfig): + Required. The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + to update. + + The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + Gets to update. Example: ``token_ttl``. + """ + + app_attest_config = proto.Field( + proto.MESSAGE, + number=1, + message='AppAttestConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeviceCheckConfig(proto.Message): + r"""An app's DeviceCheck configuration object. This configuration is + used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by DeviceCheck. It also + controls certain properties of the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used as part of + the validation process. Please register it via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + Attributes: + name (str): + Required. The relative resource name of the DeviceCheck + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from DeviceCheck tokens will be + valid. If unset, a default value of 1 hour is + assumed. Must be between 30 minutes and 7 days, + inclusive. + key_id (str): + Required. The key identifier of a private key + enabled with DeviceCheck, created in your Apple + Developer account. + private_key (str): + Required. Input only. The contents of the private key + (``.p8``) file associated with the key specified by + ``key_id``. + + For security reasons, this field will never be populated in + any response. + private_key_set (bool): + Output only. Whether the ``private_key`` field was + previously set. Since we will never return the + ``private_key`` field, this field is the only way to find + out whether it was previously set. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + token_ttl = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + key_id = proto.Field( + proto.STRING, + number=2, + ) + private_key = proto.Field( + proto.STRING, + number=3, + ) + private_key_set = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDeviceCheckConfigRequest(proto.Message): + r"""Request message for the + [GetDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.GetDeviceCheckConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetDeviceCheckConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + to retrieve, in the format + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetDeviceCheckConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.DeviceCheckConfig]): + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DeviceCheckConfig', + ) + + +class UpdateDeviceCheckConfigRequest(proto.Message): + r"""Request message for the + [UpdateDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateDeviceCheckConfig] + method. + + Attributes: + device_check_config (google.firebase.appcheck_v1beta.types.DeviceCheckConfig): + Required. The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + to update. + + The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + Gets to update. Example: ``key_id,private_key``. + """ + + device_check_config = proto.Field( + proto.MESSAGE, + number=1, + message='DeviceCheckConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class RecaptchaConfig(proto.Message): + r"""An app's reCAPTCHA v3 configuration object. This configuration is + used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by reCAPTCHA v3. It also + controls certain properties of the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Attributes: + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from reCAPTCHA tokens will be + valid. If unset, a default value of 1 day is + assumed. Must be between 30 minutes and 7 days, + inclusive. + name (str): + Required. The relative resource name of the reCAPTCHA v3 + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + site_secret (str): + Required. Input only. The site secret used to + identify your service for reCAPTCHA v3 + verification. + For security reasons, this field will never be + populated in any response. + site_secret_set (bool): + Output only. Whether the ``site_secret`` field was + previously set. Since we will never return the + ``site_secret`` field, this field is the only way to find + out whether it was previously set. + """ + + token_ttl = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + site_secret = proto.Field( + proto.STRING, + number=2, + ) + site_secret_set = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetRecaptchaConfigRequest(proto.Message): + r"""Request message for the + [GetRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.GetRecaptchaConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetRecaptchaConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + to retrieve, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetRecaptchaConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.RecaptchaConfig]): + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RecaptchaConfig', + ) + + +class UpdateRecaptchaConfigRequest(proto.Message): + r"""Request message for the + [UpdateRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateRecaptchaConfig] + method. + + Attributes: + recaptcha_config (google.firebase.appcheck_v1beta.types.RecaptchaConfig): + Required. The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. + + The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. Example: ``site_secret``. + """ + + recaptcha_config = proto.Field( + proto.MESSAGE, + number=1, + message='RecaptchaConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SafetyNetConfig(proto.Message): + r"""An app's SafetyNet configuration object. This configuration controls + certain properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate fingerprints are used + to validate tokens issued by SafetyNet; please register them via the + Firebase Console or programmatically via the `Firebase Management + Service `__. + + Attributes: + name (str): + Required. The relative resource name of the SafetyNet + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from SafetyNet tokens will be + valid. If unset, a default value of 1 hour is + assumed. Must be between 30 minutes and 7 days, + inclusive. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + token_ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class GetSafetyNetConfigRequest(proto.Message): + r"""Request message for the + [GetSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.GetSafetyNetConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetSafetyNetConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + to retrieve, in the format + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetSafetyNetConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.SafetyNetConfig]): + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SafetyNetConfig', + ) + + +class UpdateSafetyNetConfigRequest(proto.Message): + r"""Request message for the + [UpdateSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateSafetyNetConfig] + method. + + Attributes: + safety_net_config (google.firebase.appcheck_v1beta.types.SafetyNetConfig): + Required. The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + to update. + + The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + Gets to update. Example: ``token_ttl``. + """ + + safety_net_config = proto.Field( + proto.MESSAGE, + number=1, + message='SafetyNetConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DebugToken(proto.Message): + r"""A *debug token* is a secret used during the development or + integration testing of an app. It essentially allows the development + or integration testing to bypass app attestation while still + allowing App Check to enforce protection on supported production + Firebase services. + + Attributes: + name (str): + The relative resource name of the debug token, in the + format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + display_name (str): + Required. A human readable display name used + to identify this debug token. + token (str): + Input only. Immutable. The secret token itself. Must be + provided during creation, and must be a UUID4, case + insensitive. + + This field is immutable once set, and cannot be provided + during an + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + request. You can, however, delete this debug token using + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + to revoke it. + + For security reasons, this field will never be populated in + any response. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + token = proto.Field( + proto.STRING, + number=3, + ) + + +class GetDebugTokenRequest(proto.Message): + r"""Request message for the + [GetDebugToken][google.firebase.appcheck.v1beta.ConfigService.GetDebugToken] + method. + + Attributes: + name (str): + Required. The relative resource name of the debug token, in + the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDebugTokensRequest(proto.Message): + r"""Request message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + Attributes: + parent (str): + Required. The relative resource name of the parent app for + which to list each associated + [DebugToken][google.firebase.appcheck.v1beta.DebugToken], in + the format: + + :: + + projects/{project_number}/apps/{app_id} + page_size (int): + The maximum number of + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s to + return in the response. Note that an app can have at most 20 + debug tokens. + + The server may return fewer than this at its own discretion. + If no value is specified (or too large a value is + specified), the server will impose its own limit. + page_token (str): + Token returned from a previous call to + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + indicating where in the set of + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s to + resume listing. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + must match the call that provided the page token; if they do + not match, the result is undefined. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDebugTokensResponse(proto.Message): + r"""Response message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + Attributes: + debug_tokens (Sequence[google.firebase.appcheck_v1beta.types.DebugToken]): + The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s + retrieved. + next_page_token (str): + If the result list is too large to fit in a single response, + then a token is returned. If the string is empty or omitted, + then this response is the last page of results. + + This token can be used in a subsequent call to + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + to find the next group of + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s. + + Page tokens are short-lived and should not be persisted. + """ + + @property + def raw_page(self): + return self + + debug_tokens = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DebugToken', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDebugTokenRequest(proto.Message): + r"""Request message for the + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken] + method. + + Attributes: + parent (str): + Required. The relative resource name of the parent app in + which the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will be created, in the format: + + :: + + projects/{project_number}/apps/{app_id} + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + create. + + For security reasons, after creation, the ``token`` field of + the [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will never be populated in any response. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + debug_token = proto.Field( + proto.MESSAGE, + number=2, + message='DebugToken', + ) + + +class UpdateDebugTokenRequest(proto.Message): + r"""Request message for the + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + method. + + Attributes: + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + update. + + The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]'s + ``name`` field is used to identify the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + update. Example: ``display_name``. + """ + + debug_token = proto.Field( + proto.MESSAGE, + number=1, + message='DebugToken', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDebugTokenRequest(proto.Message): + r"""Request message for the + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + delete, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class Service(proto.Message): + r"""The enforcement configuration for a Firebase service + supported by App Check. + + Attributes: + name (str): + Required. The relative resource name of the service + configuration object, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase Realtime + Database) + enforcement_mode (google.firebase.appcheck_v1beta.types.Service.EnforcementMode): + Required. The App Check enforcement mode for + this service. + """ + class EnforcementMode(proto.Enum): + r"""The App Check enforcement mode for a Firebase service + supported by App Check. + """ + OFF = 0 + UNENFORCED = 1 + ENFORCED = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + enforcement_mode = proto.Field( + proto.ENUM, + number=2, + enum=EnforcementMode, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for the + [GetService][google.firebase.appcheck.v1beta.ConfigService.GetService] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [Service][google.firebase.appcheck.v1beta.Service] to + retrieve, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase Realtime + Database) + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + Attributes: + parent (str): + Required. The relative resource name of the parent project + for which to list each associated + [Service][google.firebase.appcheck.v1beta.Service], in the + format: + + :: + + projects/{project_number} + page_size (int): + The maximum number of + [Service][google.firebase.appcheck.v1beta.Service]s to + return in the response. Only explicitly configured services + are returned. + + The server may return fewer than this at its own discretion. + If no value is specified (or too large a value is + specified), the server will impose its own limit. + page_token (str): + Token returned from a previous call to + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + indicating where in the set of + [Service][google.firebase.appcheck.v1beta.Service]s to + resume listing. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + must match the call that provided the page token; if they do + not match, the result is undefined. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServicesResponse(proto.Message): + r"""Response message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + Attributes: + services (Sequence[google.firebase.appcheck_v1beta.types.Service]): + The [Service][google.firebase.appcheck.v1beta.Service]s + retrieved. + next_page_token (str): + If the result list is too large to fit in a single response, + then a token is returned. If the string is empty or omitted, + then this response is the last page of results. + + This token can be used in a subsequent call to + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + to find the next group of + [Service][google.firebase.appcheck.v1beta.Service]s. + + Page tokens are short-lived and should not be persisted. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for the + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + method as well as an individual update message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + Attributes: + service (google.firebase.appcheck_v1beta.types.Service): + Required. The + [Service][google.firebase.appcheck.v1beta.Service] to + update. + + The [Service][google.firebase.appcheck.v1beta.Service]'s + ``name`` field is used to identify the + [Service][google.firebase.appcheck.v1beta.Service] to be + updated, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase Realtime + Database) + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [Service][google.firebase.appcheck.v1beta.Service] to + update. Example: ``enforcement_mode``. + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message='Service', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateServicesRequest(proto.Message): + r"""Request message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [Service][google.firebase.appcheck.v1beta.Service] + configurations being updated, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being updated must match this field, or the entire batch + fails. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A comma-separated list of names of fields in the + [Service][google.firebase.appcheck.v1beta.Service]s to + update. Example: ``display_name``. + + If this field is present, the ``update_mask`` field in the + [UpdateServiceRequest][google.firebase.appcheck.v1beta.UpdateServiceRequest] + messages must all match this field, or the entire batch + fails and no updates will be committed. + requests (Sequence[google.firebase.appcheck_v1beta.types.UpdateServiceRequest]): + Required. The request messages specifying the + [Service][google.firebase.appcheck.v1beta.Service]s to + update. + + A maximum of 100 objects can be updated in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + requests = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='UpdateServiceRequest', + ) + + +class BatchUpdateServicesResponse(proto.Message): + r"""Response message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + Attributes: + services (Sequence[google.firebase.appcheck_v1beta.types.Service]): + [Service][google.firebase.appcheck.v1beta.Service] objects + after the updates have been applied. + """ + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/appcheck_gapic/google/firebase/appcheck_v1beta/types/token_exchange_service.py b/appcheck_gapic/google/firebase/appcheck_v1beta/types/token_exchange_service.py new file mode 100644 index 000000000..588ef501d --- /dev/null +++ b/appcheck_gapic/google/firebase/appcheck_v1beta/types/token_exchange_service.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.firebase.appcheck.v1beta', + manifest={ + 'GetPublicJwkSetRequest', + 'PublicJwkSet', + 'PublicJwk', + 'ExchangeSafetyNetTokenRequest', + 'ExchangeDeviceCheckTokenRequest', + 'ExchangeRecaptchaTokenRequest', + 'ExchangeCustomTokenRequest', + 'AttestationTokenResponse', + 'ExchangeDebugTokenRequest', + 'GenerateAppAttestChallengeRequest', + 'AppAttestChallengeResponse', + 'ExchangeAppAttestAttestationRequest', + 'ExchangeAppAttestAttestationResponse', + 'ExchangeAppAttestAssertionRequest', + }, +) + + +class GetPublicJwkSetRequest(proto.Message): + r"""Request message for the [GetPublicJwkSet][] method. + Attributes: + name (str): + Required. The relative resource name to the public JWK set. + Must always be exactly the string ``jwks``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class PublicJwkSet(proto.Message): + r"""The currently active set of public keys that can be used to verify + App Check tokens. + + This object is a JWK set as specified by `section 5 of RFC + 7517 `__. + + For security, the response **must not** be cached for longer than + one day. + + Attributes: + keys (Sequence[google.firebase.appcheck_v1beta.types.PublicJwk]): + The set of public keys. See `section 5.1 of RFC + 7517 `__. + """ + + keys = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PublicJwk', + ) + + +class PublicJwk(proto.Message): + r"""A JWK as specified by `section 4 of RFC + 7517 `__ and `section + 6.3.1 of RFC + 7518 `__. + + Attributes: + kty (str): + See `section 4.1 of RFC + 7517 `__. + use (str): + See `section 4.2 of RFC + 7517 `__. + alg (str): + See `section 4.4 of RFC + 7517 `__. + kid (str): + See `section 4.5 of RFC + 7517 `__. + n (str): + See `section 6.3.1.1 of RFC + 7518 `__. + e (str): + See `section 6.3.1.2 of RFC + 7518 `__. + """ + + kty = proto.Field( + proto.STRING, + number=1, + ) + use = proto.Field( + proto.STRING, + number=2, + ) + alg = proto.Field( + proto.STRING, + number=3, + ) + kid = proto.Field( + proto.STRING, + number=4, + ) + n = proto.Field( + proto.STRING, + number=5, + ) + e = proto.Field( + proto.STRING, + number=6, + ) + + +class ExchangeSafetyNetTokenRequest(proto.Message): + r"""Request message for the [ExchangeSafetyNetToken][] method. + Attributes: + app (str): + Required. The relative resource name of the Android app, in + the format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + safety_net_token (str): + The `SafetyNet attestation + response `__ + issued to your app. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + safety_net_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ExchangeDeviceCheckTokenRequest(proto.Message): + r"""Request message for the [ExchangeDeviceCheckToken][] method. + Attributes: + app (str): + Required. The relative resource name of the iOS app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + device_token (str): + The ``device_token`` as returned by Apple's client-side + `DeviceCheck + API `__. + This is the Base64 encoded ``Data`` (Swift) or ``NSData`` + (ObjC) object. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + device_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ExchangeRecaptchaTokenRequest(proto.Message): + r"""Request message for the [ExchangeRecaptchaToken][] method. + Attributes: + app (str): + Required. The relative resource name of the web app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + recaptcha_token (str): + The reCAPTCHA token as returned by the `reCAPTCHA v3 + JavaScript + API `__. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + recaptcha_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ExchangeCustomTokenRequest(proto.Message): + r"""Request message for the [ExchangeCustomToken][] method. + Attributes: + app (str): + Required. The relative resource name of the app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + custom_token (str): + A custom token signed using your project's + Admin SDK service account credentials. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + custom_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AttestationTokenResponse(proto.Message): + r"""Encapsulates an *App Check token*, which are used to access Firebase + services protected by App Check. + + Attributes: + attestation_token (str): + An App Check token. + + App Check tokens are signed + `JWTs `__ containing + claims that identify the attested app and Firebase project. + This token is used to access Firebase services protected by + App Check. + ttl (google.protobuf.duration_pb2.Duration): + The duration from the time this token is + minted until its expiration. This field is + intended to ease client-side token management, + since the client may have clock skew, but is + still able to accurately measure a duration. + """ + + attestation_token = proto.Field( + proto.STRING, + number=1, + ) + ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ExchangeDebugTokenRequest(proto.Message): + r"""Request message for the [ExchangeDebugToken][] method. + Attributes: + app (str): + Required. The relative resource name of the app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + debug_token (str): + A debug token secret. This string must match a debug token + secret previously created using + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken]. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + debug_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateAppAttestChallengeRequest(proto.Message): + r"""Request message for GenerateAppAttestChallenge + Attributes: + app (str): + Required. The full resource name to the iOS App. Format: + "projects/{project_id}/apps/{app_id}". + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + + +class AppAttestChallengeResponse(proto.Message): + r"""Response object for GenerateAppAttestChallenge + Attributes: + challenge (bytes): + A one time use challenge for the client to + pass to Apple's App Attest API. + ttl (google.protobuf.duration_pb2.Duration): + The duration from the time this challenge is + minted until it is expired. This field is + intended to ease client-side token management, + since the device may have clock skew, but is + still able to accurately measure a duration. + This expiration is intended to minimize the + replay window within which a single challenge + may be reused. + See AIP 142 for naming of this field. + """ + + challenge = proto.Field( + proto.BYTES, + number=1, + ) + ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ExchangeAppAttestAttestationRequest(proto.Message): + r"""Request message for ExchangeAppAttestAttestation + Attributes: + app (str): + Required. The full resource name to the iOS App. Format: + "projects/{project_id}/apps/{app_id}". + attestation_statement (bytes): + The App Attest statement as returned by + Apple's client-side App Attest API. This is the + CBOR object returned by Apple, which will be + Base64 encoded in the JSON API. + challenge (bytes): + The challenge previously generated by the FAC + backend. + key_id (bytes): + The key ID generated by App Attest for the + client app. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + attestation_statement = proto.Field( + proto.BYTES, + number=2, + ) + challenge = proto.Field( + proto.BYTES, + number=3, + ) + key_id = proto.Field( + proto.BYTES, + number=4, + ) + + +class ExchangeAppAttestAttestationResponse(proto.Message): + r"""Response message for ExchangeAppAttestAttestation and + ExchangeAppAttestDebugAttestation + + Attributes: + artifact (bytes): + An artifact that should be passed back during + the Assertion flow. + attestation_token (google.firebase.appcheck_v1beta.types.AttestationTokenResponse): + An attestation token which can be used to + access Firebase APIs. + """ + + artifact = proto.Field( + proto.BYTES, + number=1, + ) + attestation_token = proto.Field( + proto.MESSAGE, + number=2, + message='AttestationTokenResponse', + ) + + +class ExchangeAppAttestAssertionRequest(proto.Message): + r"""Request message for ExchangeAppAttestAssertion + Attributes: + app (str): + Required. The full resource name to the iOS App. Format: + "projects/{project_id}/apps/{app_id}". + artifact (bytes): + The artifact previously returned by + ExchangeAppAttestAttestation. + assertion (bytes): + The CBOR encoded assertion provided by the + Apple App Attest SDK. + challenge (bytes): + A one time challenge returned by + GenerateAppAttestChallenge. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + artifact = proto.Field( + proto.BYTES, + number=2, + ) + assertion = proto.Field( + proto.BYTES, + number=3, + ) + challenge = proto.Field( + proto.BYTES, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/appcheck_gapic/mypy.ini b/appcheck_gapic/mypy.ini new file mode 100644 index 000000000..4505b4854 --- /dev/null +++ b/appcheck_gapic/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/appcheck_gapic/noxfile.py b/appcheck_gapic/noxfile.py new file mode 100644 index 000000000..f4d26f98d --- /dev/null +++ b/appcheck_gapic/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/firebase/appcheck_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/appcheck_gapic/scripts/fixup_appcheck_v1beta_keywords.py b/appcheck_gapic/scripts/fixup_appcheck_v1beta_keywords.py new file mode 100644 index 000000000..1b666b8bf --- /dev/null +++ b/appcheck_gapic/scripts/fixup_appcheck_v1beta_keywords.py @@ -0,0 +1,205 @@ +#! /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 appcheckCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_get_app_attest_configs': ('parent', 'names', ), + 'batch_get_device_check_configs': ('parent', 'names', ), + 'batch_get_recaptcha_configs': ('parent', 'names', ), + 'batch_get_safety_net_configs': ('parent', 'names', ), + 'batch_update_services': ('parent', 'requests', 'update_mask', ), + 'create_debug_token': ('parent', 'debug_token', ), + 'delete_debug_token': ('name', ), + 'exchange_app_attest_assertion': ('app', 'artifact', 'assertion', 'challenge', ), + 'exchange_app_attest_attestation': ('app', 'attestation_statement', 'challenge', 'key_id', ), + 'exchange_custom_token': ('app', 'custom_token', ), + 'exchange_debug_token': ('app', 'debug_token', ), + 'exchange_device_check_token': ('app', 'device_token', ), + 'exchange_recaptcha_token': ('app', 'recaptcha_token', ), + 'exchange_safety_net_token': ('app', 'safety_net_token', ), + 'generate_app_attest_challenge': ('app', ), + 'get_app_attest_config': ('name', ), + 'get_debug_token': ('name', ), + 'get_device_check_config': ('name', ), + 'get_public_jwk_set': ('name', ), + 'get_recaptcha_config': ('name', ), + 'get_safety_net_config': ('name', ), + 'get_service': ('name', ), + 'list_debug_tokens': ('parent', 'page_size', 'page_token', ), + 'list_services': ('parent', 'page_size', 'page_token', ), + 'update_app_attest_config': ('app_attest_config', 'update_mask', ), + 'update_debug_token': ('debug_token', 'update_mask', ), + 'update_device_check_config': ('device_check_config', 'update_mask', ), + 'update_recaptcha_config': ('recaptcha_config', 'update_mask', ), + 'update_safety_net_config': ('safety_net_config', 'update_mask', ), + 'update_service': ('service', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=appcheckCallTransformer(), +): + """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 appcheck 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/appcheck_gapic/setup.py b/appcheck_gapic/setup.py new file mode 100644 index 000000000..bb733d494 --- /dev/null +++ b/appcheck_gapic/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-firebase-appcheck', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.firebase'), + 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/appcheck_gapic/tests/__init__.py b/appcheck_gapic/tests/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/appcheck_gapic/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/appcheck_gapic/tests/unit/__init__.py b/appcheck_gapic/tests/unit/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/appcheck_gapic/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/appcheck_gapic/tests/unit/gapic/__init__.py b/appcheck_gapic/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/appcheck_gapic/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/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/__init__.py b/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/__init__.py new file mode 100644 index 000000000..b54a5fcc4 --- /dev/null +++ b/appcheck_gapic/tests/unit/gapic/appcheck_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/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/test_config_service.py b/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/test_config_service.py new file mode 100644 index 000000000..009d1c6d2 --- /dev/null +++ b/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/test_config_service.py @@ -0,0 +1,2669 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 requests import Response +from requests.sessions import Session + +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.firebase.appcheck_v1beta.services.config_service import ConfigServiceClient +from google.firebase.appcheck_v1beta.services.config_service import pagers +from google.firebase.appcheck_v1beta.services.config_service import transports +from google.firebase.appcheck_v1beta.services.config_service.transports.base import _GOOGLE_AUTH_VERSION +from google.firebase.appcheck_v1beta.types import configuration +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_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 ConfigServiceClient._get_default_mtls_endpoint(None) is None + assert ConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ConfigServiceClient, +]) +def test_config_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'firebaseappcheck.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConfigServiceRestTransport, "rest"), +]) +def test_config_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ConfigServiceClient, +]) +def test_config_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'firebaseappcheck.googleapis.com:443' + + +def test_config_service_client_get_transport_class(): + transport = ConfigServiceClient.get_transport_class() + available_transports = [ + transports.ConfigServiceRestTransport, + ] + assert transport in available_transports + + transport = ConfigServiceClient.get_transport_class("rest") + assert transport == transports.ConfigServiceRestTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConfigServiceClient, transports.ConfigServiceRestTransport, "rest"), +]) +@mock.patch.object(ConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigServiceClient)) +def test_config_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ConfigServiceClient, '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(ConfigServiceClient, '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, + ) + + # 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, + ) + + # 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, + ) + + # 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConfigServiceClient, transports.ConfigServiceRestTransport, "rest", "true"), + (ConfigServiceClient, transports.ConfigServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigServiceClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_config_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + 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, + ) + + # 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, + ) + + # 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConfigServiceClient, transports.ConfigServiceRestTransport, "rest"), +]) +def test_config_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConfigServiceClient, transports.ConfigServiceRestTransport, "rest"), +]) +def test_config_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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, + ) + + +def test_get_app_attest_config_rest(transport: str = 'rest', request_type=configuration.GetAppAttestConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.AppAttestConfig( + name='name_value', + token_ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.AppAttestConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_app_attest_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.AppAttestConfig) + assert response.name == 'name_value' + assert response.token_ttl == duration_pb2.Duration(seconds=751) + + +def test_get_app_attest_config_rest_from_dict(): + test_get_app_attest_config_rest(request_type=dict) + + +def test_get_app_attest_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.AppAttestConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.AppAttestConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_app_attest_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_app_attest_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_app_attest_config( + configuration.GetAppAttestConfigRequest(), + name='name_value', + ) + + +def test_batch_get_app_attest_configs_rest(transport: str = 'rest', request_type=configuration.BatchGetAppAttestConfigsRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetAppAttestConfigsResponse( + configs=[configuration.AppAttestConfig(name='name_value')], + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetAppAttestConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_app_attest_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.BatchGetAppAttestConfigsResponse) + assert response.configs == [configuration.AppAttestConfig(name='name_value')] + + +def test_batch_get_app_attest_configs_rest_from_dict(): + test_batch_get_app_attest_configs_rest(request_type=dict) + + +def test_batch_get_app_attest_configs_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetAppAttestConfigsResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetAppAttestConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_get_app_attest_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + + +def test_batch_get_app_attest_configs_rest_flattened_error(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_get_app_attest_configs( + configuration.BatchGetAppAttestConfigsRequest(), + parent='parent_value', + ) + + +def test_update_app_attest_config_rest(transport: str = 'rest', request_type=configuration.UpdateAppAttestConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.AppAttestConfig( + name='name_value', + token_ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.AppAttestConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_app_attest_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.AppAttestConfig) + assert response.name == 'name_value' + assert response.token_ttl == duration_pb2.Duration(seconds=751) + + +def test_update_app_attest_config_rest_from_dict(): + test_update_app_attest_config_rest(request_type=dict) + + +def test_update_app_attest_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.AppAttestConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.AppAttestConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + app_attest_config = configuration.AppAttestConfig(name='name_value') + update_mask = field_mask_pb2.FieldMask(paths=['paths_value']) + client.update_app_attest_config( + app_attest_config=app_attest_config, + update_mask=update_mask, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert configuration.AppAttestConfig.to_json(app_attest_config, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + assert field_mask_pb2.FieldMask.to_json(update_mask, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_update_app_attest_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_app_attest_config( + configuration.UpdateAppAttestConfigRequest(), + app_attest_config=configuration.AppAttestConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_device_check_config_rest(transport: str = 'rest', request_type=configuration.GetDeviceCheckConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DeviceCheckConfig( + name='name_value', + token_ttl=duration_pb2.Duration(seconds=751), + key_id='key_id_value', + private_key='private_key_value', + private_key_set=True, + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.DeviceCheckConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_device_check_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.DeviceCheckConfig) + assert response.name == 'name_value' + assert response.token_ttl == duration_pb2.Duration(seconds=751) + assert response.key_id == 'key_id_value' + assert response.private_key == 'private_key_value' + assert response.private_key_set is True + + +def test_get_device_check_config_rest_from_dict(): + test_get_device_check_config_rest(request_type=dict) + + +def test_get_device_check_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DeviceCheckConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.DeviceCheckConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_device_check_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_device_check_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_device_check_config( + configuration.GetDeviceCheckConfigRequest(), + name='name_value', + ) + + +def test_batch_get_device_check_configs_rest(transport: str = 'rest', request_type=configuration.BatchGetDeviceCheckConfigsRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetDeviceCheckConfigsResponse( + configs=[configuration.DeviceCheckConfig(name='name_value')], + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetDeviceCheckConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_device_check_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.BatchGetDeviceCheckConfigsResponse) + assert response.configs == [configuration.DeviceCheckConfig(name='name_value')] + + +def test_batch_get_device_check_configs_rest_from_dict(): + test_batch_get_device_check_configs_rest(request_type=dict) + + +def test_batch_get_device_check_configs_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetDeviceCheckConfigsResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetDeviceCheckConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_get_device_check_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + + +def test_batch_get_device_check_configs_rest_flattened_error(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_get_device_check_configs( + configuration.BatchGetDeviceCheckConfigsRequest(), + parent='parent_value', + ) + + +def test_update_device_check_config_rest(transport: str = 'rest', request_type=configuration.UpdateDeviceCheckConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DeviceCheckConfig( + name='name_value', + token_ttl=duration_pb2.Duration(seconds=751), + key_id='key_id_value', + private_key='private_key_value', + private_key_set=True, + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.DeviceCheckConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_device_check_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.DeviceCheckConfig) + assert response.name == 'name_value' + assert response.token_ttl == duration_pb2.Duration(seconds=751) + assert response.key_id == 'key_id_value' + assert response.private_key == 'private_key_value' + assert response.private_key_set is True + + +def test_update_device_check_config_rest_from_dict(): + test_update_device_check_config_rest(request_type=dict) + + +def test_update_device_check_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DeviceCheckConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.DeviceCheckConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + device_check_config = configuration.DeviceCheckConfig(name='name_value') + update_mask = field_mask_pb2.FieldMask(paths=['paths_value']) + client.update_device_check_config( + device_check_config=device_check_config, + update_mask=update_mask, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert configuration.DeviceCheckConfig.to_json(device_check_config, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + assert field_mask_pb2.FieldMask.to_json(update_mask, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_update_device_check_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_device_check_config( + configuration.UpdateDeviceCheckConfigRequest(), + device_check_config=configuration.DeviceCheckConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_recaptcha_config_rest(transport: str = 'rest', request_type=configuration.GetRecaptchaConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.RecaptchaConfig( + token_ttl=duration_pb2.Duration(seconds=751), + name='name_value', + site_secret='site_secret_value', + site_secret_set=True, + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.RecaptchaConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_recaptcha_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.RecaptchaConfig) + assert response.token_ttl == duration_pb2.Duration(seconds=751) + assert response.name == 'name_value' + assert response.site_secret == 'site_secret_value' + assert response.site_secret_set is True + + +def test_get_recaptcha_config_rest_from_dict(): + test_get_recaptcha_config_rest(request_type=dict) + + +def test_get_recaptcha_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.RecaptchaConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.RecaptchaConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_recaptcha_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_recaptcha_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_recaptcha_config( + configuration.GetRecaptchaConfigRequest(), + name='name_value', + ) + + +def test_batch_get_recaptcha_configs_rest(transport: str = 'rest', request_type=configuration.BatchGetRecaptchaConfigsRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetRecaptchaConfigsResponse( + configs=[configuration.RecaptchaConfig(token_ttl=duration_pb2.Duration(seconds=751))], + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetRecaptchaConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_recaptcha_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.BatchGetRecaptchaConfigsResponse) + assert response.configs == [configuration.RecaptchaConfig(token_ttl=duration_pb2.Duration(seconds=751))] + + +def test_batch_get_recaptcha_configs_rest_from_dict(): + test_batch_get_recaptcha_configs_rest(request_type=dict) + + +def test_batch_get_recaptcha_configs_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetRecaptchaConfigsResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetRecaptchaConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_get_recaptcha_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + + +def test_batch_get_recaptcha_configs_rest_flattened_error(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_get_recaptcha_configs( + configuration.BatchGetRecaptchaConfigsRequest(), + parent='parent_value', + ) + + +def test_update_recaptcha_config_rest(transport: str = 'rest', request_type=configuration.UpdateRecaptchaConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.RecaptchaConfig( + token_ttl=duration_pb2.Duration(seconds=751), + name='name_value', + site_secret='site_secret_value', + site_secret_set=True, + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.RecaptchaConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_recaptcha_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.RecaptchaConfig) + assert response.token_ttl == duration_pb2.Duration(seconds=751) + assert response.name == 'name_value' + assert response.site_secret == 'site_secret_value' + assert response.site_secret_set is True + + +def test_update_recaptcha_config_rest_from_dict(): + test_update_recaptcha_config_rest(request_type=dict) + + +def test_update_recaptcha_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.RecaptchaConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.RecaptchaConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + recaptcha_config = configuration.RecaptchaConfig(token_ttl=duration_pb2.Duration(seconds=751)) + update_mask = field_mask_pb2.FieldMask(paths=['paths_value']) + client.update_recaptcha_config( + recaptcha_config=recaptcha_config, + update_mask=update_mask, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert configuration.RecaptchaConfig.to_json(recaptcha_config, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + assert field_mask_pb2.FieldMask.to_json(update_mask, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_update_recaptcha_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_recaptcha_config( + configuration.UpdateRecaptchaConfigRequest(), + recaptcha_config=configuration.RecaptchaConfig(token_ttl=duration_pb2.Duration(seconds=751)), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_safety_net_config_rest(transport: str = 'rest', request_type=configuration.GetSafetyNetConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.SafetyNetConfig( + name='name_value', + token_ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.SafetyNetConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_safety_net_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.SafetyNetConfig) + assert response.name == 'name_value' + assert response.token_ttl == duration_pb2.Duration(seconds=751) + + +def test_get_safety_net_config_rest_from_dict(): + test_get_safety_net_config_rest(request_type=dict) + + +def test_get_safety_net_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.SafetyNetConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.SafetyNetConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_safety_net_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_safety_net_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_safety_net_config( + configuration.GetSafetyNetConfigRequest(), + name='name_value', + ) + + +def test_batch_get_safety_net_configs_rest(transport: str = 'rest', request_type=configuration.BatchGetSafetyNetConfigsRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetSafetyNetConfigsResponse( + configs=[configuration.SafetyNetConfig(name='name_value')], + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetSafetyNetConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_safety_net_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.BatchGetSafetyNetConfigsResponse) + assert response.configs == [configuration.SafetyNetConfig(name='name_value')] + + +def test_batch_get_safety_net_configs_rest_from_dict(): + test_batch_get_safety_net_configs_rest(request_type=dict) + + +def test_batch_get_safety_net_configs_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchGetSafetyNetConfigsResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchGetSafetyNetConfigsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_get_safety_net_configs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + + +def test_batch_get_safety_net_configs_rest_flattened_error(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_get_safety_net_configs( + configuration.BatchGetSafetyNetConfigsRequest(), + parent='parent_value', + ) + + +def test_update_safety_net_config_rest(transport: str = 'rest', request_type=configuration.UpdateSafetyNetConfigRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.SafetyNetConfig( + name='name_value', + token_ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.SafetyNetConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_safety_net_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.SafetyNetConfig) + assert response.name == 'name_value' + assert response.token_ttl == duration_pb2.Duration(seconds=751) + + +def test_update_safety_net_config_rest_from_dict(): + test_update_safety_net_config_rest(request_type=dict) + + +def test_update_safety_net_config_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.SafetyNetConfig() + + # Wrap the value into a proper Response obj + json_return_value = configuration.SafetyNetConfig.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + safety_net_config = configuration.SafetyNetConfig(name='name_value') + update_mask = field_mask_pb2.FieldMask(paths=['paths_value']) + client.update_safety_net_config( + safety_net_config=safety_net_config, + update_mask=update_mask, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert configuration.SafetyNetConfig.to_json(safety_net_config, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + assert field_mask_pb2.FieldMask.to_json(update_mask, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_update_safety_net_config_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_safety_net_config( + configuration.UpdateSafetyNetConfigRequest(), + safety_net_config=configuration.SafetyNetConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_debug_token_rest(transport: str = 'rest', request_type=configuration.GetDebugTokenRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DebugToken( + name='name_value', + display_name='display_name_value', + token='token_value', + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.DebugToken.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_debug_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.DebugToken) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.token == 'token_value' + + +def test_get_debug_token_rest_from_dict(): + test_get_debug_token_rest(request_type=dict) + + +def test_get_debug_token_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DebugToken() + + # Wrap the value into a proper Response obj + json_return_value = configuration.DebugToken.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_debug_token( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_debug_token_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_debug_token( + configuration.GetDebugTokenRequest(), + name='name_value', + ) + + +def test_list_debug_tokens_rest(transport: str = 'rest', request_type=configuration.ListDebugTokensRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.ListDebugTokensResponse( + debug_tokens=[configuration.DebugToken(name='name_value')], + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.ListDebugTokensResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_debug_tokens(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDebugTokensPager) + assert response.debug_tokens == [configuration.DebugToken(name='name_value')] + assert response.next_page_token == 'next_page_token_value' + + +def test_list_debug_tokens_rest_from_dict(): + test_list_debug_tokens_rest(request_type=dict) + + +def test_list_debug_tokens_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.ListDebugTokensResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.ListDebugTokensResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_debug_tokens( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + + +def test_list_debug_tokens_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_debug_tokens( + configuration.ListDebugTokensRequest(), + parent='parent_value', + ) + + +def test_list_debug_tokens_pager(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Set the response as a series of pages + response = ( + configuration.ListDebugTokensResponse( + debug_tokens=[ + configuration.DebugToken(), + configuration.DebugToken(), + configuration.DebugToken(), + ], + next_page_token='abc', + ), + configuration.ListDebugTokensResponse( + debug_tokens=[], + next_page_token='def', + ), + configuration.ListDebugTokensResponse( + debug_tokens=[ + configuration.DebugToken(), + ], + next_page_token='ghi', + ), + configuration.ListDebugTokensResponse( + debug_tokens=[ + configuration.DebugToken(), + configuration.DebugToken(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(configuration.ListDebugTokensResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_debug_tokens(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, configuration.DebugToken) + for i in results) + + pages = list(client.list_debug_tokens(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_debug_token_rest(transport: str = 'rest', request_type=configuration.CreateDebugTokenRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DebugToken( + name='name_value', + display_name='display_name_value', + token='token_value', + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.DebugToken.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_debug_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.DebugToken) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.token == 'token_value' + + +def test_create_debug_token_rest_from_dict(): + test_create_debug_token_rest(request_type=dict) + + +def test_create_debug_token_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DebugToken() + + # Wrap the value into a proper Response obj + json_return_value = configuration.DebugToken.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + debug_token = configuration.DebugToken(name='name_value') + client.create_debug_token( + parent='parent_value', + debug_token=debug_token, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + assert configuration.DebugToken.to_json(debug_token, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_create_debug_token_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_debug_token( + configuration.CreateDebugTokenRequest(), + parent='parent_value', + debug_token=configuration.DebugToken(name='name_value'), + ) + + +def test_update_debug_token_rest(transport: str = 'rest', request_type=configuration.UpdateDebugTokenRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DebugToken( + name='name_value', + display_name='display_name_value', + token='token_value', + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.DebugToken.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_debug_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.DebugToken) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.token == 'token_value' + + +def test_update_debug_token_rest_from_dict(): + test_update_debug_token_rest(request_type=dict) + + +def test_update_debug_token_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.DebugToken() + + # Wrap the value into a proper Response obj + json_return_value = configuration.DebugToken.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + debug_token = configuration.DebugToken(name='name_value') + update_mask = field_mask_pb2.FieldMask(paths=['paths_value']) + client.update_debug_token( + debug_token=debug_token, + update_mask=update_mask, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert configuration.DebugToken.to_json(debug_token, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + assert field_mask_pb2.FieldMask.to_json(update_mask, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_update_debug_token_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_debug_token( + configuration.UpdateDebugTokenRequest(), + debug_token=configuration.DebugToken(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_debug_token_rest(transport: str = 'rest', request_type=configuration.DeleteDebugTokenRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + json_return_value = empty_pb2.Empty.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_debug_token(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_debug_token_rest_from_dict(): + test_delete_debug_token_rest(request_type=dict) + + +def test_delete_debug_token_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + json_return_value = empty_pb2.Empty.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_debug_token( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_delete_debug_token_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_debug_token( + configuration.DeleteDebugTokenRequest(), + name='name_value', + ) + + +def test_get_service_rest(transport: str = 'rest', request_type=configuration.GetServiceRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.Service( + name='name_value', + enforcement_mode=configuration.Service.EnforcementMode.UNENFORCED, + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.Service.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.Service) + assert response.name == 'name_value' + assert response.enforcement_mode == configuration.Service.EnforcementMode.UNENFORCED + + +def test_get_service_rest_from_dict(): + test_get_service_rest(request_type=dict) + + +def test_get_service_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.Service() + + # Wrap the value into a proper Response obj + json_return_value = configuration.Service.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_service_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_service( + configuration.GetServiceRequest(), + name='name_value', + ) + + +def test_list_services_rest(transport: str = 'rest', request_type=configuration.ListServicesRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.ListServicesResponse( + services=[configuration.Service(name='name_value')], + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.ListServicesResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.services == [configuration.Service(name='name_value')] + assert response.next_page_token == 'next_page_token_value' + + +def test_list_services_rest_from_dict(): + test_list_services_rest(request_type=dict) + + +def test_list_services_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.ListServicesResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.ListServicesResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'parent_value' in http_call[1] + str(body) + str(params) + + +def test_list_services_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_services( + configuration.ListServicesRequest(), + parent='parent_value', + ) + + +def test_list_services_pager(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Set the response as a series of pages + response = ( + configuration.ListServicesResponse( + services=[ + configuration.Service(), + configuration.Service(), + configuration.Service(), + ], + next_page_token='abc', + ), + configuration.ListServicesResponse( + services=[], + next_page_token='def', + ), + configuration.ListServicesResponse( + services=[ + configuration.Service(), + ], + next_page_token='ghi', + ), + configuration.ListServicesResponse( + services=[ + configuration.Service(), + configuration.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(configuration.ListServicesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, configuration.Service) + for i in results) + + pages = list(client.list_services(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_service_rest(transport: str = 'rest', request_type=configuration.UpdateServiceRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.Service( + name='name_value', + enforcement_mode=configuration.Service.EnforcementMode.UNENFORCED, + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.Service.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.Service) + assert response.name == 'name_value' + assert response.enforcement_mode == configuration.Service.EnforcementMode.UNENFORCED + + +def test_update_service_rest_from_dict(): + test_update_service_rest(request_type=dict) + + +def test_update_service_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.Service() + + # Wrap the value into a proper Response obj + json_return_value = configuration.Service.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + service = configuration.Service(name='name_value') + update_mask = field_mask_pb2.FieldMask(paths=['paths_value']) + client.update_service( + service=service, + update_mask=update_mask, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert configuration.Service.to_json(service, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + assert field_mask_pb2.FieldMask.to_json(update_mask, including_default_value_fields=False, use_integers_for_enums=False) in http_call[1] + str(body) + str(params) + + +def test_update_service_rest_flattened_error(): + client = ConfigServiceClient( + credentials=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_service( + configuration.UpdateServiceRequest(), + service=configuration.Service(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_batch_update_services_rest(transport: str = 'rest', request_type=configuration.BatchUpdateServicesRequest): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchUpdateServicesResponse( + services=[configuration.Service(name='name_value')], + ) + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchUpdateServicesResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_update_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, configuration.BatchUpdateServicesResponse) + assert response.services == [configuration.Service(name='name_value')] + + +def test_batch_update_services_rest_from_dict(): + test_batch_update_services_rest(request_type=dict) + + +def test_batch_update_services_rest_flattened(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = configuration.BatchUpdateServicesResponse() + + # Wrap the value into a proper Response obj + json_return_value = configuration.BatchUpdateServicesResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_update_services( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_batch_update_services_rest_flattened_error(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_services( + configuration.BatchUpdateServicesRequest(), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConfigServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize("transport_class", [ + transports.ConfigServiceRestTransport, +]) +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_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.firebase.appcheck_v1beta.services.config_service.transports.ConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_app_attest_config', + 'batch_get_app_attest_configs', + 'update_app_attest_config', + 'get_device_check_config', + 'batch_get_device_check_configs', + 'update_device_check_config', + 'get_recaptcha_config', + 'batch_get_recaptcha_configs', + 'update_recaptcha_config', + 'get_safety_net_config', + 'batch_get_safety_net_configs', + 'update_safety_net_config', + 'get_debug_token', + 'list_debug_tokens', + 'create_debug_token', + 'update_debug_token', + 'delete_debug_token', + 'get_service', + 'list_services', + 'update_service', + 'batch_update_services', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_config_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.firebase.appcheck_v1beta.services.config_service.transports.ConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_config_service_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.firebase.appcheck_v1beta.services.config_service.transports.ConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', + ), + quota_project_id="octopus", + ) + + +def test_config_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.firebase.appcheck_v1beta.services.config_service.transports.ConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_config_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ConfigServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_config_service_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) + ConfigServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/firebase',), + quota_project_id=None, + ) + + +def test_config_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ConfigServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + +def test_config_service_host_no_port(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='firebaseappcheck.googleapis.com'), + ) + assert client.transport._host == 'firebaseappcheck.googleapis.com:443' + + +def test_config_service_host_with_port(): + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='firebaseappcheck.googleapis.com:8000'), + ) + assert client.transport._host == 'firebaseappcheck.googleapis.com:8000' + + +def test_app_attest_config_path(): + project = "squid" + app = "clam" + expected = "projects/{project}/apps/{app}/appAttestConfig".format(project=project, app=app, ) + actual = ConfigServiceClient.app_attest_config_path(project, app) + assert expected == actual + + +def test_parse_app_attest_config_path(): + expected = { + "project": "whelk", + "app": "octopus", + } + path = ConfigServiceClient.app_attest_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_app_attest_config_path(path) + assert expected == actual + +def test_debug_token_path(): + project = "oyster" + app = "nudibranch" + debug_token = "cuttlefish" + expected = "projects/{project}/apps/{app}/debugTokens/{debug_token}".format(project=project, app=app, debug_token=debug_token, ) + actual = ConfigServiceClient.debug_token_path(project, app, debug_token) + assert expected == actual + + +def test_parse_debug_token_path(): + expected = { + "project": "mussel", + "app": "winkle", + "debug_token": "nautilus", + } + path = ConfigServiceClient.debug_token_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_debug_token_path(path) + assert expected == actual + +def test_device_check_config_path(): + project = "scallop" + app = "abalone" + expected = "projects/{project}/apps/{app}/deviceCheckConfig".format(project=project, app=app, ) + actual = ConfigServiceClient.device_check_config_path(project, app) + assert expected == actual + + +def test_parse_device_check_config_path(): + expected = { + "project": "squid", + "app": "clam", + } + path = ConfigServiceClient.device_check_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_device_check_config_path(path) + assert expected == actual + +def test_recaptcha_config_path(): + project = "whelk" + app = "octopus" + expected = "projects/{project}/apps/{app}/recaptchaConfig".format(project=project, app=app, ) + actual = ConfigServiceClient.recaptcha_config_path(project, app) + assert expected == actual + + +def test_parse_recaptcha_config_path(): + expected = { + "project": "oyster", + "app": "nudibranch", + } + path = ConfigServiceClient.recaptcha_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_recaptcha_config_path(path) + assert expected == actual + +def test_safety_net_config_path(): + project = "cuttlefish" + app = "mussel" + expected = "projects/{project}/apps/{app}/safetyNetConfig".format(project=project, app=app, ) + actual = ConfigServiceClient.safety_net_config_path(project, app) + assert expected == actual + + +def test_parse_safety_net_config_path(): + expected = { + "project": "winkle", + "app": "nautilus", + } + path = ConfigServiceClient.safety_net_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_safety_net_config_path(path) + assert expected == actual + +def test_service_path(): + project = "scallop" + service = "abalone" + expected = "projects/{project}/services/{service}".format(project=project, service=service, ) + actual = ConfigServiceClient.service_path(project, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "squid", + "service": "clam", + } + path = ConfigServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigServiceClient.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.ConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = ConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ConfigServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/test_token_exchange_service.py b/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/test_token_exchange_service.py new file mode 100644 index 000000000..c70255b2c --- /dev/null +++ b/appcheck_gapic/tests/unit/gapic/appcheck_v1beta/test_token_exchange_service.py @@ -0,0 +1,1372 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 requests import Response +from requests.sessions import Session + +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.firebase.appcheck_v1beta.services.token_exchange_service import TokenExchangeServiceClient +from google.firebase.appcheck_v1beta.services.token_exchange_service import transports +from google.firebase.appcheck_v1beta.services.token_exchange_service.transports.base import _GOOGLE_AUTH_VERSION +from google.firebase.appcheck_v1beta.types import token_exchange_service +from google.oauth2 import service_account +from google.protobuf import duration_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 TokenExchangeServiceClient._get_default_mtls_endpoint(None) is None + assert TokenExchangeServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TokenExchangeServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TokenExchangeServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TokenExchangeServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TokenExchangeServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + TokenExchangeServiceClient, +]) +def test_token_exchange_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'firebaseappcheck.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.TokenExchangeServiceRestTransport, "rest"), +]) +def test_token_exchange_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + TokenExchangeServiceClient, +]) +def test_token_exchange_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'firebaseappcheck.googleapis.com:443' + + +def test_token_exchange_service_client_get_transport_class(): + transport = TokenExchangeServiceClient.get_transport_class() + available_transports = [ + transports.TokenExchangeServiceRestTransport, + ] + assert transport in available_transports + + transport = TokenExchangeServiceClient.get_transport_class("rest") + assert transport == transports.TokenExchangeServiceRestTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TokenExchangeServiceClient, transports.TokenExchangeServiceRestTransport, "rest"), +]) +@mock.patch.object(TokenExchangeServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TokenExchangeServiceClient)) +def test_token_exchange_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(TokenExchangeServiceClient, '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(TokenExchangeServiceClient, '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, + ) + + # 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, + ) + + # 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, + ) + + # 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (TokenExchangeServiceClient, transports.TokenExchangeServiceRestTransport, "rest", "true"), + (TokenExchangeServiceClient, transports.TokenExchangeServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(TokenExchangeServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TokenExchangeServiceClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_token_exchange_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + 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, + ) + + # 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, + ) + + # 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TokenExchangeServiceClient, transports.TokenExchangeServiceRestTransport, "rest"), +]) +def test_token_exchange_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TokenExchangeServiceClient, transports.TokenExchangeServiceRestTransport, "rest"), +]) +def test_token_exchange_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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, + ) + + +def test_get_public_jwk_set_rest(transport: str = 'rest', request_type=token_exchange_service.GetPublicJwkSetRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.PublicJwkSet( + keys=[token_exchange_service.PublicJwk(kty='kty_value')], + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.PublicJwkSet.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_public_jwk_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.PublicJwkSet) + assert response.keys == [token_exchange_service.PublicJwk(kty='kty_value')] + + +def test_get_public_jwk_set_rest_from_dict(): + test_get_public_jwk_set_rest(request_type=dict) + + +def test_get_public_jwk_set_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.PublicJwkSet() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.PublicJwkSet.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_public_jwk_set( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + assert 'name_value' in http_call[1] + str(body) + str(params) + + +def test_get_public_jwk_set_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_public_jwk_set( + token_exchange_service.GetPublicJwkSetRequest(), + name='name_value', + ) + + +def test_exchange_safety_net_token_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeSafetyNetTokenRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse( + attestation_token='attestation_token_value', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_safety_net_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AttestationTokenResponse) + assert response.attestation_token == 'attestation_token_value' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_exchange_safety_net_token_rest_from_dict(): + test_exchange_safety_net_token_rest(request_type=dict) + + +def test_exchange_safety_net_token_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_safety_net_token( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_safety_net_token_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_safety_net_token( + token_exchange_service.ExchangeSafetyNetTokenRequest(), + ) + + +def test_exchange_device_check_token_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeDeviceCheckTokenRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse( + attestation_token='attestation_token_value', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_device_check_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AttestationTokenResponse) + assert response.attestation_token == 'attestation_token_value' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_exchange_device_check_token_rest_from_dict(): + test_exchange_device_check_token_rest(request_type=dict) + + +def test_exchange_device_check_token_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_device_check_token( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_device_check_token_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_device_check_token( + token_exchange_service.ExchangeDeviceCheckTokenRequest(), + ) + + +def test_exchange_recaptcha_token_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeRecaptchaTokenRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse( + attestation_token='attestation_token_value', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_recaptcha_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AttestationTokenResponse) + assert response.attestation_token == 'attestation_token_value' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_exchange_recaptcha_token_rest_from_dict(): + test_exchange_recaptcha_token_rest(request_type=dict) + + +def test_exchange_recaptcha_token_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_recaptcha_token( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_recaptcha_token_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_recaptcha_token( + token_exchange_service.ExchangeRecaptchaTokenRequest(), + ) + + +def test_exchange_custom_token_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeCustomTokenRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse( + attestation_token='attestation_token_value', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_custom_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AttestationTokenResponse) + assert response.attestation_token == 'attestation_token_value' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_exchange_custom_token_rest_from_dict(): + test_exchange_custom_token_rest(request_type=dict) + + +def test_exchange_custom_token_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_custom_token( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_custom_token_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_custom_token( + token_exchange_service.ExchangeCustomTokenRequest(), + ) + + +def test_exchange_debug_token_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeDebugTokenRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse( + attestation_token='attestation_token_value', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_debug_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AttestationTokenResponse) + assert response.attestation_token == 'attestation_token_value' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_exchange_debug_token_rest_from_dict(): + test_exchange_debug_token_rest(request_type=dict) + + +def test_exchange_debug_token_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_debug_token( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_debug_token_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_debug_token( + token_exchange_service.ExchangeDebugTokenRequest(), + ) + + +def test_generate_app_attest_challenge_rest(transport: str = 'rest', request_type=token_exchange_service.GenerateAppAttestChallengeRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AppAttestChallengeResponse( + challenge=b'challenge_blob', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AppAttestChallengeResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_app_attest_challenge(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AppAttestChallengeResponse) + assert response.challenge == b'challenge_blob' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_generate_app_attest_challenge_rest_from_dict(): + test_generate_app_attest_challenge_rest(request_type=dict) + + +def test_generate_app_attest_challenge_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AppAttestChallengeResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AppAttestChallengeResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_app_attest_challenge( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_generate_app_attest_challenge_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_app_attest_challenge( + token_exchange_service.GenerateAppAttestChallengeRequest(), + ) + + +def test_exchange_app_attest_attestation_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeAppAttestAttestationRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.ExchangeAppAttestAttestationResponse( + artifact=b'artifact_blob', + attestation_token=token_exchange_service.AttestationTokenResponse(attestation_token='attestation_token_value'), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.ExchangeAppAttestAttestationResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_app_attest_attestation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.ExchangeAppAttestAttestationResponse) + assert response.artifact == b'artifact_blob' + assert response.attestation_token == token_exchange_service.AttestationTokenResponse(attestation_token='attestation_token_value') + + +def test_exchange_app_attest_attestation_rest_from_dict(): + test_exchange_app_attest_attestation_rest(request_type=dict) + + +def test_exchange_app_attest_attestation_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.ExchangeAppAttestAttestationResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.ExchangeAppAttestAttestationResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_app_attest_attestation( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_app_attest_attestation_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_app_attest_attestation( + token_exchange_service.ExchangeAppAttestAttestationRequest(), + ) + + +def test_exchange_app_attest_assertion_rest(transport: str = 'rest', request_type=token_exchange_service.ExchangeAppAttestAssertionRequest): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse( + attestation_token='attestation_token_value', + ttl=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.exchange_app_attest_assertion(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, token_exchange_service.AttestationTokenResponse) + assert response.attestation_token == 'attestation_token_value' + assert response.ttl == duration_pb2.Duration(seconds=751) + + +def test_exchange_app_attest_assertion_rest_from_dict(): + test_exchange_app_attest_assertion_rest(request_type=dict) + + +def test_exchange_app_attest_assertion_rest_flattened(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = token_exchange_service.AttestationTokenResponse() + + # Wrap the value into a proper Response obj + json_return_value = token_exchange_service.AttestationTokenResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.exchange_app_attest_assertion( + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get('data') + params = http_params.get('params') + + +def test_exchange_app_attest_assertion_rest_flattened_error(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.exchange_app_attest_assertion( + token_exchange_service.ExchangeAppAttestAssertionRequest(), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TokenExchangeServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TokenExchangeServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TokenExchangeServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TokenExchangeServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TokenExchangeServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TokenExchangeServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TokenExchangeServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize("transport_class", [ + transports.TokenExchangeServiceRestTransport, +]) +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_token_exchange_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TokenExchangeServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_token_exchange_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.firebase.appcheck_v1beta.services.token_exchange_service.transports.TokenExchangeServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TokenExchangeServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_public_jwk_set', + 'exchange_safety_net_token', + 'exchange_device_check_token', + 'exchange_recaptcha_token', + 'exchange_custom_token', + 'exchange_debug_token', + 'generate_app_attest_challenge', + 'exchange_app_attest_attestation', + 'exchange_app_attest_assertion', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_token_exchange_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.firebase.appcheck_v1beta.services.token_exchange_service.transports.TokenExchangeServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TokenExchangeServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_token_exchange_service_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.firebase.appcheck_v1beta.services.token_exchange_service.transports.TokenExchangeServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TokenExchangeServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', + ), + quota_project_id="octopus", + ) + + +def test_token_exchange_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.firebase.appcheck_v1beta.services.token_exchange_service.transports.TokenExchangeServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TokenExchangeServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_token_exchange_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TokenExchangeServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_token_exchange_service_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) + TokenExchangeServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/firebase',), + quota_project_id=None, + ) + + +def test_token_exchange_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.TokenExchangeServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + +def test_token_exchange_service_host_no_port(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='firebaseappcheck.googleapis.com'), + ) + assert client.transport._host == 'firebaseappcheck.googleapis.com:443' + + +def test_token_exchange_service_host_with_port(): + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='firebaseappcheck.googleapis.com:8000'), + ) + assert client.transport._host == 'firebaseappcheck.googleapis.com:8000' + + +def test_public_jwk_set_path(): + expected = "jwks".format() + actual = TokenExchangeServiceClient.public_jwk_set_path() + assert expected == actual + + +def test_parse_public_jwk_set_path(): + expected = { + } + path = TokenExchangeServiceClient.public_jwk_set_path(**expected) + + # Check that the path construction is reversible. + actual = TokenExchangeServiceClient.parse_public_jwk_set_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TokenExchangeServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = TokenExchangeServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TokenExchangeServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = TokenExchangeServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = TokenExchangeServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TokenExchangeServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TokenExchangeServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = TokenExchangeServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TokenExchangeServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = TokenExchangeServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = TokenExchangeServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TokenExchangeServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TokenExchangeServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = TokenExchangeServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TokenExchangeServiceClient.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.TokenExchangeServiceTransport, '_prep_wrapped_messages') as prep: + client = TokenExchangeServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TokenExchangeServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TokenExchangeServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/firebase_admin/_token_gen.py b/firebase_admin/_token_gen.py index 32c109d5d..9ca60b97d 100644 --- a/firebase_admin/_token_gen.py +++ b/firebase_admin/_token_gen.py @@ -47,6 +47,8 @@ MAX_TOKEN_LIFETIME_SECONDS = int(datetime.timedelta(hours=1).total_seconds()) FIREBASE_AUDIENCE = ('https://identitytoolkit.googleapis.com/google.' 'identity.identitytoolkit.v1.IdentityToolkit') +FIREBASE_APP_CHECK_AUDIENCE = ('https://firebaseappcheck.googleapis.com/google.' + 'firebase.appcheck.v1beta.TokenExchangeService') RESERVED_CLAIMS = set([ 'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'firebase', 'iat', 'iss', 'jti', 'nbf', 'nonce', 'sub' @@ -206,6 +208,31 @@ def create_custom_token(self, uid, developer_claims=None, tenant_id=None): raise TokenSignError(msg, error) + def create_custom_token_fac(self, app_id): + """Builds and signs a Firebase custom FAC token.""" + + if not app_id or not isinstance(app_id, str): + raise ValueError('app_id must be a string.') + + signing_provider = self.signing_provider + now = int(time.time()) + payload = { + 'iss': signing_provider.signer_email, + 'sub': signing_provider.signer_email, + 'aud': FIREBASE_APP_CHECK_AUDIENCE, + 'app_id': app_id, + 'iat': now, + 'exp': now + MAX_TOKEN_LIFETIME_SECONDS, + } + + header = {'alg': signing_provider.alg, 'typ': 'JWT'} + try: + return jwt.encode(signing_provider.signer, payload, header=header) + except google.auth.exceptions.TransportError as error: + msg = 'Failed to sign custom token. {0}'.format(error) + raise TokenSignError(msg, error) + + def create_session_cookie(self, id_token, expires_in): """Creates a session cookie from the provided ID token.""" id_token = id_token.decode('utf-8') if isinstance(id_token, bytes) else id_token diff --git a/firebase_admin/appcheck.py b/firebase_admin/appcheck.py new file mode 100644 index 000000000..c7cdc3e54 --- /dev/null +++ b/firebase_admin/appcheck.py @@ -0,0 +1,77 @@ +# Copyright 2021 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Firebase App Check module. +""" + +try: + from google.firebase import appcheck_v1beta + existing = globals().keys() + for key, value in appcheck_v1beta.__dict__.items(): + if not key.startswith('_') and key not in existing: + globals()[key] = value +except ImportError: + raise ImportError('Failed to import the Firebase App Check library for Python. Make sure ' + 'to install the "google-cloud-firestore" module.') + +from firebase_admin import _token_gen +from firebase_admin import _utils + + +_FAC_ATTRIBUTE = '_appcheck' + + +def _get_fac_service(app=None): + return _utils.get_app_service(app, _FAC_ATTRIBUTE, _AppCheckClient.from_app) + +def create_token(app_id, app=None): + project_id = _get_fac_service(app).project_id() + token = _get_fac_service(app).token_generator().create_custom_token_fac(app_id) + payload = {} + payload['app'] = 'projects/{project_number}/apps/{app_id}'.format( + project_number=project_id, app_id=app_id) + payload['custom_token'] = token + return _get_fac_service(app).get().exchange_custom_token(payload) + + +class _AppCheckClient: + """Holds a Firebase App Check client instance.""" + + def __init__(self, credentials, project, token_generator): + self._project = project + self._client = appcheck_v1beta.services.token_exchange_service.TokenExchangeServiceClient( + credentials=credentials, transport='rest') + self._token_generator = token_generator + + def get(self): + return self._client + + def project_id(self): + return self._project + + def token_generator(self): + return self._token_generator + + @classmethod + def from_app(cls, app): + """Creates a new _FirestoreClient for the specified app.""" + credentials = app.credential.get_credential() + project = app.project_id + token_generator = _token_gen.TokenGenerator(app, http_client=None) + if not project: + raise ValueError( + 'Project ID is required to access Firestore. Either set the projectId option, ' + 'or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + 'environment variable.') + return _AppCheckClient(credentials, project, token_generator) diff --git a/google/firebase/appcheck/__init__.py b/google/firebase/appcheck/__init__.py new file mode 100644 index 000000000..0f67a580f --- /dev/null +++ b/google/firebase/appcheck/__init__.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.firebase.appcheck_v1beta.services.config_service.client import ConfigServiceClient +from google.firebase.appcheck_v1beta.services.token_exchange_service.client import TokenExchangeServiceClient + +from google.firebase.appcheck_v1beta.types.configuration import AppAttestConfig +from google.firebase.appcheck_v1beta.types.configuration import BatchGetAppAttestConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetAppAttestConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchGetDeviceCheckConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetDeviceCheckConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchGetRecaptchaConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetRecaptchaConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchGetSafetyNetConfigsRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchGetSafetyNetConfigsResponse +from google.firebase.appcheck_v1beta.types.configuration import BatchUpdateServicesRequest +from google.firebase.appcheck_v1beta.types.configuration import BatchUpdateServicesResponse +from google.firebase.appcheck_v1beta.types.configuration import CreateDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import DebugToken +from google.firebase.appcheck_v1beta.types.configuration import DeleteDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import DeviceCheckConfig +from google.firebase.appcheck_v1beta.types.configuration import GetAppAttestConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import GetDeviceCheckConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetRecaptchaConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetSafetyNetConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import GetServiceRequest +from google.firebase.appcheck_v1beta.types.configuration import ListDebugTokensRequest +from google.firebase.appcheck_v1beta.types.configuration import ListDebugTokensResponse +from google.firebase.appcheck_v1beta.types.configuration import ListServicesRequest +from google.firebase.appcheck_v1beta.types.configuration import ListServicesResponse +from google.firebase.appcheck_v1beta.types.configuration import RecaptchaConfig +from google.firebase.appcheck_v1beta.types.configuration import SafetyNetConfig +from google.firebase.appcheck_v1beta.types.configuration import Service +from google.firebase.appcheck_v1beta.types.configuration import UpdateAppAttestConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateDebugTokenRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateDeviceCheckConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateRecaptchaConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateSafetyNetConfigRequest +from google.firebase.appcheck_v1beta.types.configuration import UpdateServiceRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import AppAttestChallengeResponse +from google.firebase.appcheck_v1beta.types.token_exchange_service import AttestationTokenResponse +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeAppAttestAssertionRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeAppAttestAttestationRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeAppAttestAttestationResponse +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeCustomTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeDebugTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeDeviceCheckTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeRecaptchaTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import ExchangeSafetyNetTokenRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import GenerateAppAttestChallengeRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import GetPublicJwkSetRequest +from google.firebase.appcheck_v1beta.types.token_exchange_service import PublicJwk +from google.firebase.appcheck_v1beta.types.token_exchange_service import PublicJwkSet + +__all__ = ('ConfigServiceClient', + 'TokenExchangeServiceClient', + 'AppAttestConfig', + 'BatchGetAppAttestConfigsRequest', + 'BatchGetAppAttestConfigsResponse', + 'BatchGetDeviceCheckConfigsRequest', + 'BatchGetDeviceCheckConfigsResponse', + 'BatchGetRecaptchaConfigsRequest', + 'BatchGetRecaptchaConfigsResponse', + 'BatchGetSafetyNetConfigsRequest', + 'BatchGetSafetyNetConfigsResponse', + 'BatchUpdateServicesRequest', + 'BatchUpdateServicesResponse', + 'CreateDebugTokenRequest', + 'DebugToken', + 'DeleteDebugTokenRequest', + 'DeviceCheckConfig', + 'GetAppAttestConfigRequest', + 'GetDebugTokenRequest', + 'GetDeviceCheckConfigRequest', + 'GetRecaptchaConfigRequest', + 'GetSafetyNetConfigRequest', + 'GetServiceRequest', + 'ListDebugTokensRequest', + 'ListDebugTokensResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'RecaptchaConfig', + 'SafetyNetConfig', + 'Service', + 'UpdateAppAttestConfigRequest', + 'UpdateDebugTokenRequest', + 'UpdateDeviceCheckConfigRequest', + 'UpdateRecaptchaConfigRequest', + 'UpdateSafetyNetConfigRequest', + 'UpdateServiceRequest', + 'AppAttestChallengeResponse', + 'AttestationTokenResponse', + 'ExchangeAppAttestAssertionRequest', + 'ExchangeAppAttestAttestationRequest', + 'ExchangeAppAttestAttestationResponse', + 'ExchangeCustomTokenRequest', + 'ExchangeDebugTokenRequest', + 'ExchangeDeviceCheckTokenRequest', + 'ExchangeRecaptchaTokenRequest', + 'ExchangeSafetyNetTokenRequest', + 'GenerateAppAttestChallengeRequest', + 'GetPublicJwkSetRequest', + 'PublicJwk', + 'PublicJwkSet', +) diff --git a/google/firebase/appcheck/py.typed b/google/firebase/appcheck/py.typed new file mode 100644 index 000000000..c16f5d9cc --- /dev/null +++ b/google/firebase/appcheck/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-firebase-appcheck package uses inline types. diff --git a/google/firebase/appcheck_v1beta/__init__.py b/google/firebase/appcheck_v1beta/__init__.py new file mode 100644 index 000000000..eedc1ad9e --- /dev/null +++ b/google/firebase/appcheck_v1beta/__init__.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.config_service import ConfigServiceClient +from .services.token_exchange_service import TokenExchangeServiceClient + +from .types.configuration import AppAttestConfig +from .types.configuration import BatchGetAppAttestConfigsRequest +from .types.configuration import BatchGetAppAttestConfigsResponse +from .types.configuration import BatchGetDeviceCheckConfigsRequest +from .types.configuration import BatchGetDeviceCheckConfigsResponse +from .types.configuration import BatchGetRecaptchaConfigsRequest +from .types.configuration import BatchGetRecaptchaConfigsResponse +from .types.configuration import BatchGetSafetyNetConfigsRequest +from .types.configuration import BatchGetSafetyNetConfigsResponse +from .types.configuration import BatchUpdateServicesRequest +from .types.configuration import BatchUpdateServicesResponse +from .types.configuration import CreateDebugTokenRequest +from .types.configuration import DebugToken +from .types.configuration import DeleteDebugTokenRequest +from .types.configuration import DeviceCheckConfig +from .types.configuration import GetAppAttestConfigRequest +from .types.configuration import GetDebugTokenRequest +from .types.configuration import GetDeviceCheckConfigRequest +from .types.configuration import GetRecaptchaConfigRequest +from .types.configuration import GetSafetyNetConfigRequest +from .types.configuration import GetServiceRequest +from .types.configuration import ListDebugTokensRequest +from .types.configuration import ListDebugTokensResponse +from .types.configuration import ListServicesRequest +from .types.configuration import ListServicesResponse +from .types.configuration import RecaptchaConfig +from .types.configuration import SafetyNetConfig +from .types.configuration import Service +from .types.configuration import UpdateAppAttestConfigRequest +from .types.configuration import UpdateDebugTokenRequest +from .types.configuration import UpdateDeviceCheckConfigRequest +from .types.configuration import UpdateRecaptchaConfigRequest +from .types.configuration import UpdateSafetyNetConfigRequest +from .types.configuration import UpdateServiceRequest +from .types.token_exchange_service import AppAttestChallengeResponse +from .types.token_exchange_service import AttestationTokenResponse +from .types.token_exchange_service import ExchangeAppAttestAssertionRequest +from .types.token_exchange_service import ExchangeAppAttestAttestationRequest +from .types.token_exchange_service import ExchangeAppAttestAttestationResponse +from .types.token_exchange_service import ExchangeCustomTokenRequest +from .types.token_exchange_service import ExchangeDebugTokenRequest +from .types.token_exchange_service import ExchangeDeviceCheckTokenRequest +from .types.token_exchange_service import ExchangeRecaptchaTokenRequest +from .types.token_exchange_service import ExchangeSafetyNetTokenRequest +from .types.token_exchange_service import GenerateAppAttestChallengeRequest +from .types.token_exchange_service import GetPublicJwkSetRequest +from .types.token_exchange_service import PublicJwk +from .types.token_exchange_service import PublicJwkSet + +__all__ = ( +'AppAttestChallengeResponse', +'AppAttestConfig', +'AttestationTokenResponse', +'BatchGetAppAttestConfigsRequest', +'BatchGetAppAttestConfigsResponse', +'BatchGetDeviceCheckConfigsRequest', +'BatchGetDeviceCheckConfigsResponse', +'BatchGetRecaptchaConfigsRequest', +'BatchGetRecaptchaConfigsResponse', +'BatchGetSafetyNetConfigsRequest', +'BatchGetSafetyNetConfigsResponse', +'BatchUpdateServicesRequest', +'BatchUpdateServicesResponse', +'ConfigServiceClient', +'CreateDebugTokenRequest', +'DebugToken', +'DeleteDebugTokenRequest', +'DeviceCheckConfig', +'ExchangeAppAttestAssertionRequest', +'ExchangeAppAttestAttestationRequest', +'ExchangeAppAttestAttestationResponse', +'ExchangeCustomTokenRequest', +'ExchangeDebugTokenRequest', +'ExchangeDeviceCheckTokenRequest', +'ExchangeRecaptchaTokenRequest', +'ExchangeSafetyNetTokenRequest', +'GenerateAppAttestChallengeRequest', +'GetAppAttestConfigRequest', +'GetDebugTokenRequest', +'GetDeviceCheckConfigRequest', +'GetPublicJwkSetRequest', +'GetRecaptchaConfigRequest', +'GetSafetyNetConfigRequest', +'GetServiceRequest', +'ListDebugTokensRequest', +'ListDebugTokensResponse', +'ListServicesRequest', +'ListServicesResponse', +'PublicJwk', +'PublicJwkSet', +'RecaptchaConfig', +'SafetyNetConfig', +'Service', +'TokenExchangeServiceClient', +'UpdateAppAttestConfigRequest', +'UpdateDebugTokenRequest', +'UpdateDeviceCheckConfigRequest', +'UpdateRecaptchaConfigRequest', +'UpdateSafetyNetConfigRequest', +'UpdateServiceRequest', +) diff --git a/google/firebase/appcheck_v1beta/gapic_metadata.json b/google/firebase/appcheck_v1beta/gapic_metadata.json new file mode 100644 index 000000000..8b6aaa508 --- /dev/null +++ b/google/firebase/appcheck_v1beta/gapic_metadata.json @@ -0,0 +1,177 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.firebase.appcheck_v1beta", + "protoPackage": "google.firebase.appcheck.v1beta", + "schema": "1.0", + "services": { + "ConfigService": { + "clients": { + "rest": { + "libraryClient": "ConfigServiceClient", + "rpcs": { + "BatchGetAppAttestConfigs": { + "methods": [ + "batch_get_app_attest_configs" + ] + }, + "BatchGetDeviceCheckConfigs": { + "methods": [ + "batch_get_device_check_configs" + ] + }, + "BatchGetRecaptchaConfigs": { + "methods": [ + "batch_get_recaptcha_configs" + ] + }, + "BatchGetSafetyNetConfigs": { + "methods": [ + "batch_get_safety_net_configs" + ] + }, + "BatchUpdateServices": { + "methods": [ + "batch_update_services" + ] + }, + "CreateDebugToken": { + "methods": [ + "create_debug_token" + ] + }, + "DeleteDebugToken": { + "methods": [ + "delete_debug_token" + ] + }, + "GetAppAttestConfig": { + "methods": [ + "get_app_attest_config" + ] + }, + "GetDebugToken": { + "methods": [ + "get_debug_token" + ] + }, + "GetDeviceCheckConfig": { + "methods": [ + "get_device_check_config" + ] + }, + "GetRecaptchaConfig": { + "methods": [ + "get_recaptcha_config" + ] + }, + "GetSafetyNetConfig": { + "methods": [ + "get_safety_net_config" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListDebugTokens": { + "methods": [ + "list_debug_tokens" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateAppAttestConfig": { + "methods": [ + "update_app_attest_config" + ] + }, + "UpdateDebugToken": { + "methods": [ + "update_debug_token" + ] + }, + "UpdateDeviceCheckConfig": { + "methods": [ + "update_device_check_config" + ] + }, + "UpdateRecaptchaConfig": { + "methods": [ + "update_recaptcha_config" + ] + }, + "UpdateSafetyNetConfig": { + "methods": [ + "update_safety_net_config" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "TokenExchangeService": { + "clients": { + "rest": { + "libraryClient": "TokenExchangeServiceClient", + "rpcs": { + "ExchangeAppAttestAssertion": { + "methods": [ + "exchange_app_attest_assertion" + ] + }, + "ExchangeAppAttestAttestation": { + "methods": [ + "exchange_app_attest_attestation" + ] + }, + "ExchangeCustomToken": { + "methods": [ + "exchange_custom_token" + ] + }, + "ExchangeDebugToken": { + "methods": [ + "exchange_debug_token" + ] + }, + "ExchangeDeviceCheckToken": { + "methods": [ + "exchange_device_check_token" + ] + }, + "ExchangeRecaptchaToken": { + "methods": [ + "exchange_recaptcha_token" + ] + }, + "ExchangeSafetyNetToken": { + "methods": [ + "exchange_safety_net_token" + ] + }, + "GenerateAppAttestChallenge": { + "methods": [ + "generate_app_attest_challenge" + ] + }, + "GetPublicJwkSet": { + "methods": [ + "get_public_jwk_set" + ] + } + } + } + } + } + } +} diff --git a/google/firebase/appcheck_v1beta/py.typed b/google/firebase/appcheck_v1beta/py.typed new file mode 100644 index 000000000..c16f5d9cc --- /dev/null +++ b/google/firebase/appcheck_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-firebase-appcheck package uses inline types. diff --git a/google/firebase/appcheck_v1beta/services/__init__.py b/google/firebase/appcheck_v1beta/services/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/google/firebase/appcheck_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/google/firebase/appcheck_v1beta/services/config_service/__init__.py b/google/firebase/appcheck_v1beta/services/config_service/__init__.py new file mode 100644 index 000000000..7aaf88e2b --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/config_service/__init__.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ConfigServiceClient + +__all__ = ( + 'ConfigServiceClient', +) diff --git a/google/firebase/appcheck_v1beta/services/config_service/client.py b/google/firebase/appcheck_v1beta/services/config_service/client.py new file mode 100644 index 000000000..c5de8c6cc --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/config_service/client.py @@ -0,0 +1,2467 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.firebase.appcheck_v1beta.services.config_service import pagers +from google.firebase.appcheck_v1beta.types import configuration +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.rest import ConfigServiceRestTransport + + +class ConfigServiceClientMeta(type): + """Metaclass for the ConfigService 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[ConfigServiceTransport]] + _transport_registry["rest"] = ConfigServiceRestTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ConfigServiceTransport]: + """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 ConfigServiceClient(metaclass=ConfigServiceClientMeta): + """Manages configuration parameters used by the + [TokenExchangeService][google.firebase.appcheck.v1beta.TokenExchangeService] + and enforcement settings for Firebase services protected by App + Check. + """ + + @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 = "firebaseappcheck.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: + ConfigServiceClient: 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: + ConfigServiceClient: 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) -> ConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def app_attest_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified app_attest_config string.""" + return "projects/{project}/apps/{app}/appAttestConfig".format(project=project, app=app, ) + + @staticmethod + def parse_app_attest_config_path(path: str) -> Dict[str,str]: + """Parses a app_attest_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/appAttestConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def debug_token_path(project: str,app: str,debug_token: str,) -> str: + """Returns a fully-qualified debug_token string.""" + return "projects/{project}/apps/{app}/debugTokens/{debug_token}".format(project=project, app=app, debug_token=debug_token, ) + + @staticmethod + def parse_debug_token_path(path: str) -> Dict[str,str]: + """Parses a debug_token path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/debugTokens/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def device_check_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified device_check_config string.""" + return "projects/{project}/apps/{app}/deviceCheckConfig".format(project=project, app=app, ) + + @staticmethod + def parse_device_check_config_path(path: str) -> Dict[str,str]: + """Parses a device_check_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/deviceCheckConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def recaptcha_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified recaptcha_config string.""" + return "projects/{project}/apps/{app}/recaptchaConfig".format(project=project, app=app, ) + + @staticmethod + def parse_recaptcha_config_path(path: str) -> Dict[str,str]: + """Parses a recaptcha_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/recaptchaConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def safety_net_config_path(project: str,app: str,) -> str: + """Returns a fully-qualified safety_net_config string.""" + return "projects/{project}/apps/{app}/safetyNetConfig".format(project=project, app=app, ) + + @staticmethod + def parse_safety_net_config_path(path: str) -> Dict[str,str]: + """Parses a safety_net_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/apps/(?P.+?)/safetyNetConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/services/{service}".format(project=project, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ConfigServiceTransport]): 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, ConfigServiceTransport): + # transport is a ConfigServiceTransport 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, + ) + + def get_app_attest_config(self, + request: configuration.GetAppAttestConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Gets the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + for the specified app. + + Args: + request (google.firebase.appcheck_v1beta.types.GetAppAttestConfigRequest): + The request object. Request message for the + [GetAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.GetAppAttestConfig] + method. + name (str): + Required. The relative resource name of the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + + 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.firebase.appcheck_v1beta.types.AppAttestConfig: + An app's App Attest configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetAppAttestConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetAppAttestConfigRequest): + request = configuration.GetAppAttestConfigRequest(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_app_attest_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 batch_get_app_attest_configs(self, + request: configuration.BatchGetAppAttestConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetAppAttestConfigsResponse: + r"""Gets the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + for the specified list of apps atomically. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetAppAttestConfigsRequest): + The request object. Request message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + parent (str): + Required. The parent project name shared by all + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetAppAttestConfigsResponse: + Response message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + 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 configuration.BatchGetAppAttestConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetAppAttestConfigsRequest): + request = configuration.BatchGetAppAttestConfigsRequest(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.batch_get_app_attest_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, + ) + + # Done; return the response. + return response + + def update_app_attest_config(self, + request: configuration.UpdateAppAttestConfigRequest = None, + *, + app_attest_config: configuration.AppAttestConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Updates the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange AppAttest tokens for App Check tokens. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateAppAttestConfigRequest): + The request object. Request message for the + [UpdateAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateAppAttestConfig] + method. + app_attest_config (google.firebase.appcheck_v1beta.types.AppAttestConfig): + Required. The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + to update. + + The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + + This corresponds to the ``app_attest_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + Gets to update. Example: ``token_ttl``. + + 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.firebase.appcheck_v1beta.types.AppAttestConfig: + An app's App Attest configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([app_attest_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 configuration.UpdateAppAttestConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateAppAttestConfigRequest): + request = configuration.UpdateAppAttestConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app_attest_config is not None: + request.app_attest_config = app_attest_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_app_attest_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app_attest_config.name", request.app_attest_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_device_check_config(self, + request: configuration.GetDeviceCheckConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Gets the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + for the specified app. + + For security reasons, the + [``private_key``][google.firebase.appcheck.v1beta.DeviceCheckConfig.private_key] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.GetDeviceCheckConfigRequest): + The request object. Request message for the + [GetDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.GetDeviceCheckConfig] + method. + name (str): + Required. The relative resource name of the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + + 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.firebase.appcheck_v1beta.types.DeviceCheckConfig: + An app's DeviceCheck configuration object. This configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by + DeviceCheck. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetDeviceCheckConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetDeviceCheckConfigRequest): + request = configuration.GetDeviceCheckConfigRequest(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_device_check_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 batch_get_device_check_configs(self, + request: configuration.BatchGetDeviceCheckConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetDeviceCheckConfigsResponse: + r"""Gets the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + for the specified list of apps atomically. + + For security reasons, the + [``private_key``][google.firebase.appcheck.v1beta.DeviceCheckConfig.private_key] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetDeviceCheckConfigsRequest): + The request object. Request message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + parent (str): + Required. The parent project name shared by all + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetDeviceCheckConfigsResponse: + Response message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + 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 configuration.BatchGetDeviceCheckConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetDeviceCheckConfigsRequest): + request = configuration.BatchGetDeviceCheckConfigsRequest(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.batch_get_device_check_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, + ) + + # Done; return the response. + return response + + def update_device_check_config(self, + request: configuration.UpdateDeviceCheckConfigRequest = None, + *, + device_check_config: configuration.DeviceCheckConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Updates the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange DeviceCheck tokens for App Check tokens. + + For security reasons, the + [``private_key``][google.firebase.appcheck.v1beta.DeviceCheckConfig.private_key] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateDeviceCheckConfigRequest): + The request object. Request message for the + [UpdateDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateDeviceCheckConfig] + method. + device_check_config (google.firebase.appcheck_v1beta.types.DeviceCheckConfig): + Required. The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + to update. + + The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + + This corresponds to the ``device_check_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + Gets to update. Example: ``key_id,private_key``. + + 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.firebase.appcheck_v1beta.types.DeviceCheckConfig: + An app's DeviceCheck configuration object. This configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by + DeviceCheck. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is + used as part of the validation process. Please + register it via the Firebase Console or + programmatically via the [Firebase Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.iosApps/patch). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([device_check_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 configuration.UpdateDeviceCheckConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateDeviceCheckConfigRequest): + request = configuration.UpdateDeviceCheckConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if device_check_config is not None: + request.device_check_config = device_check_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_device_check_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("device_check_config.name", request.device_check_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_recaptcha_config(self, + request: configuration.GetRecaptchaConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Gets the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + for the specified app. + + For security reasons, the + [``site_secret``][google.firebase.appcheck.v1beta.RecaptchaConfig.site_secret] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.GetRecaptchaConfigRequest): + The request object. Request message for the + [GetRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.GetRecaptchaConfig] + method. + name (str): + Required. The relative resource name of the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + + 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.firebase.appcheck_v1beta.types.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by + reCAPTCHA v3. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetRecaptchaConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetRecaptchaConfigRequest): + request = configuration.GetRecaptchaConfigRequest(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_recaptcha_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 batch_get_recaptcha_configs(self, + request: configuration.BatchGetRecaptchaConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetRecaptchaConfigsResponse: + r"""Gets the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + for the specified list of apps atomically. + + For security reasons, the + [``site_secret``][google.firebase.appcheck.v1beta.RecaptchaConfig.site_secret] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetRecaptchaConfigsRequest): + The request object. Request message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + parent (str): + Required. The parent project name shared by all + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetRecaptchaConfigsResponse: + Response message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + 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 configuration.BatchGetRecaptchaConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetRecaptchaConfigsRequest): + request = configuration.BatchGetRecaptchaConfigsRequest(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.batch_get_recaptcha_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, + ) + + # Done; return the response. + return response + + def update_recaptcha_config(self, + request: configuration.UpdateRecaptchaConfigRequest = None, + *, + recaptcha_config: configuration.RecaptchaConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Updates the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange reCAPTCHA tokens for App Check tokens. + + For security reasons, the + [``site_secret``][google.firebase.appcheck.v1beta.RecaptchaConfig.site_secret] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateRecaptchaConfigRequest): + The request object. Request message for the + [UpdateRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateRecaptchaConfig] + method. + recaptcha_config (google.firebase.appcheck_v1beta.types.RecaptchaConfig): + Required. The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. + + The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + + This corresponds to the ``recaptcha_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. Example: ``site_secret``. + + 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.firebase.appcheck_v1beta.types.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by + reCAPTCHA v3. It also controls certain properties of + the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([recaptcha_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 configuration.UpdateRecaptchaConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateRecaptchaConfigRequest): + request = configuration.UpdateRecaptchaConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if recaptcha_config is not None: + request.recaptcha_config = recaptcha_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_recaptcha_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("recaptcha_config.name", request.recaptcha_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_safety_net_config(self, + request: configuration.GetSafetyNetConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Gets the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + for the specified app. + + Args: + request (google.firebase.appcheck_v1beta.types.GetSafetyNetConfigRequest): + The request object. Request message for the + [GetSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.GetSafetyNetConfig] + method. + name (str): + Required. The relative resource name of the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + + 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.firebase.appcheck_v1beta.types.SafetyNetConfig: + An app's SafetyNet configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase + Console or programmatically via the [Firebase + Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.androidApps.sha/create). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetSafetyNetConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetSafetyNetConfigRequest): + request = configuration.GetSafetyNetConfigRequest(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_safety_net_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 batch_get_safety_net_configs(self, + request: configuration.BatchGetSafetyNetConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetSafetyNetConfigsResponse: + r"""Gets the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + for the specified list of apps atomically. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchGetSafetyNetConfigsRequest): + The request object. Request message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + parent (str): + Required. The parent project name shared by all + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any + resource being retrieved must match this field, or the + entire batch fails. + + 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.firebase.appcheck_v1beta.types.BatchGetSafetyNetConfigsResponse: + Response message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + 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 configuration.BatchGetSafetyNetConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchGetSafetyNetConfigsRequest): + request = configuration.BatchGetSafetyNetConfigsRequest(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.batch_get_safety_net_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, + ) + + # Done; return the response. + return response + + def update_safety_net_config(self, + request: configuration.UpdateSafetyNetConfigRequest = None, + *, + safety_net_config: configuration.SafetyNetConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Updates the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + for the specified app. + + While this configuration is incomplete or invalid, the app will + be unable to exchange SafetyNet tokens for App Check tokens. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateSafetyNetConfigRequest): + The request object. Request message for the + [UpdateSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateSafetyNetConfig] + method. + safety_net_config (google.firebase.appcheck_v1beta.types.SafetyNetConfig): + Required. The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + to update. + + The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]'s + ``name`` field is used to identify the configuration to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + + This corresponds to the ``safety_net_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + Gets to update. Example: ``token_ttl``. + + 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.firebase.appcheck_v1beta.types.SafetyNetConfig: + An app's SafetyNet configuration object. This configuration controls certain + properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase + Console or programmatically via the [Firebase + Management + Service](\ https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.androidApps.sha/create). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([safety_net_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 configuration.UpdateSafetyNetConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateSafetyNetConfigRequest): + request = configuration.UpdateSafetyNetConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if safety_net_config is not None: + request.safety_net_config = safety_net_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_safety_net_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("safety_net_config.name", request.safety_net_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_debug_token(self, + request: configuration.GetDebugTokenRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Gets the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]. + + For security reasons, the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.GetDebugTokenRequest): + The request object. Request message for the + [GetDebugToken][google.firebase.appcheck.v1beta.ConfigService.GetDebugToken] + method. + name (str): + Required. The relative resource name of the debug token, + in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.DebugToken: + A *debug token* is a secret used during the development or integration + testing of an app. It essentially allows the + development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetDebugTokenRequest): + request = configuration.GetDebugTokenRequest(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_debug_token] + + # Certain fields should be 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_debug_tokens(self, + request: configuration.ListDebugTokensRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDebugTokensPager: + r"""Lists all + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s for + the specified app. + + For security reasons, the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field is never populated in the response. + + Args: + request (google.firebase.appcheck_v1beta.types.ListDebugTokensRequest): + The request object. Request message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + parent (str): + Required. The relative resource name of the parent app + for which to list each associated + [DebugToken][google.firebase.appcheck.v1beta.DebugToken], + in the format: + + :: + + projects/{project_number}/apps/{app_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.services.config_service.pagers.ListDebugTokensPager: + Response message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + 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 configuration.ListDebugTokensRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.ListDebugTokensRequest): + request = configuration.ListDebugTokensRequest(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_debug_tokens] + + # Certain fields should be provided 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.ListDebugTokensPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_debug_token(self, + request: configuration.CreateDebugTokenRequest = None, + *, + parent: str = None, + debug_token: configuration.DebugToken = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Creates a new + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] for the + specified app. + + For security reasons, after the creation operation completes, + the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field cannot be updated or retrieved, but you can revoke the + debug token using + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken]. + + Each app can have a maximum of 20 debug tokens. + + Args: + request (google.firebase.appcheck_v1beta.types.CreateDebugTokenRequest): + The request object. Request message for the + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken] + method. + parent (str): + Required. The relative resource name of the parent app + in which the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will be created, in the format: + + :: + + projects/{project_number}/apps/{app_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to create. + + For security reasons, after creation, the ``token`` + field of the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will never be populated in any response. + + This corresponds to the ``debug_token`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.DebugToken: + A *debug token* is a secret used during the development or integration + testing of an app. It essentially allows the + development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, debug_token]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a configuration.CreateDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.CreateDebugTokenRequest): + request = configuration.CreateDebugTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if debug_token is not None: + request.debug_token = debug_token + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_debug_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_debug_token(self, + request: configuration.UpdateDebugTokenRequest = None, + *, + debug_token: configuration.DebugToken = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Updates the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]. + + For security reasons, the + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + field cannot be updated, nor will it be populated in the + response, but you can revoke the debug token using + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken]. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateDebugTokenRequest): + The request object. Request message for the + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + method. + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to update. + + The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]'s + ``name`` field is used to identify the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + + This corresponds to the ``debug_token`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to update. Example: ``display_name``. + + 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.firebase.appcheck_v1beta.types.DebugToken: + A *debug token* is a secret used during the development or integration + testing of an app. It essentially allows the + development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([debug_token, 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 configuration.UpdateDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateDebugTokenRequest): + request = configuration.UpdateDebugTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if debug_token is not None: + request.debug_token = debug_token + 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_debug_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("debug_token.name", request.debug_token.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_debug_token(self, + request: configuration.DeleteDebugTokenRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]. + + A deleted debug token cannot be used to exchange for an App + Check token. Use this method when you suspect the secret + [``token``][google.firebase.appcheck.v1beta.DebugToken.token] + has been compromised or when you no longer need the debug token. + + Args: + request (google.firebase.appcheck_v1beta.types.DeleteDebugTokenRequest): + The request object. Request message for the + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + method. + name (str): + Required. The relative resource name of the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + to delete, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a configuration.DeleteDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.DeleteDebugTokenRequest): + request = configuration.DeleteDebugTokenRequest(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_debug_token] + + # Certain fields should be 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_service(self, + request: configuration.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Gets the [Service][google.firebase.appcheck.v1beta.Service] + configuration for the specified service name. + + Args: + request (google.firebase.appcheck_v1beta.types.GetServiceRequest): + The request object. Request message for the + [GetService][google.firebase.appcheck.v1beta.ConfigService.GetService] + method. + name (str): + Required. The relative resource name of the + [Service][google.firebase.appcheck.v1beta.Service] to + retrieve, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase + Realtime Database) + + 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.firebase.appcheck_v1beta.types.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 configuration.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.GetServiceRequest): + request = configuration.GetServiceRequest(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_service] + + # Certain fields should be 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_services(self, + request: configuration.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""Lists all [Service][google.firebase.appcheck.v1beta.Service] + configurations for the specified project. + + Only [Service][google.firebase.appcheck.v1beta.Service]s which + were explicitly configured using + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + or + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + will be returned. + + Args: + request (google.firebase.appcheck_v1beta.types.ListServicesRequest): + The request object. Request message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + parent (str): + Required. The relative resource name of the parent + project for which to list each associated + [Service][google.firebase.appcheck.v1beta.Service], in + the format: + + :: + + projects/{project_number} + + 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.firebase.appcheck_v1beta.services.config_service.pagers.ListServicesPager: + Response message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + 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 configuration.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.ListServicesRequest): + request = configuration.ListServicesRequest(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_services] + + # Certain fields should be provided 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.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: configuration.UpdateServiceRequest = None, + *, + service: configuration.Service = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Updates the specified + [Service][google.firebase.appcheck.v1beta.Service] + configuration. + + Args: + request (google.firebase.appcheck_v1beta.types.UpdateServiceRequest): + The request object. Request message for the + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + method as well as an individual update message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + service (google.firebase.appcheck_v1beta.types.Service): + Required. The + [Service][google.firebase.appcheck.v1beta.Service] to + update. + + The [Service][google.firebase.appcheck.v1beta.Service]'s + ``name`` field is used to identify the + [Service][google.firebase.appcheck.v1beta.Service] to be + updated, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase + Realtime Database) + + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in + the [Service][google.firebase.appcheck.v1beta.Service] + to update. Example: ``enforcement_mode``. + + 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.firebase.appcheck_v1beta.types.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, 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 configuration.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.UpdateServiceRequest): + request = configuration.UpdateServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if service is not None: + request.service = service + 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_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service.name", request.service.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_services(self, + request: configuration.BatchUpdateServicesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchUpdateServicesResponse: + r"""Updates the specified + [Service][google.firebase.appcheck.v1beta.Service] + configurations atomically. + + Args: + request (google.firebase.appcheck_v1beta.types.BatchUpdateServicesRequest): + The request object. Request message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + 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.firebase.appcheck_v1beta.types.BatchUpdateServicesResponse: + Response message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a configuration.BatchUpdateServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, configuration.BatchUpdateServicesRequest): + request = configuration.BatchUpdateServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_services] + + # Certain fields should be provided 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-firebase-appcheck", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ConfigServiceClient", +) diff --git a/google/firebase/appcheck_v1beta/services/config_service/pagers.py b/google/firebase/appcheck_v1beta/services/config_service/pagers.py new file mode 100644 index 000000000..35893403e --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/config_service/pagers.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.firebase.appcheck_v1beta.types import configuration + + +class ListDebugTokensPager: + """A pager for iterating through ``list_debug_tokens`` requests. + + This class thinly wraps an initial + :class:`google.firebase.appcheck_v1beta.types.ListDebugTokensResponse` object, and + provides an ``__iter__`` method to iterate through its + ``debug_tokens`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDebugTokens`` requests and continue to iterate + through the ``debug_tokens`` field on the + corresponding responses. + + All the usual :class:`google.firebase.appcheck_v1beta.types.ListDebugTokensResponse` + 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[..., configuration.ListDebugTokensResponse], + request: configuration.ListDebugTokensRequest, + response: configuration.ListDebugTokensResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.firebase.appcheck_v1beta.types.ListDebugTokensRequest): + The initial request object. + response (google.firebase.appcheck_v1beta.types.ListDebugTokensResponse): + 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 = configuration.ListDebugTokensRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[configuration.ListDebugTokensResponse]: + 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[configuration.DebugToken]: + for page in self.pages: + yield from page.debug_tokens + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.firebase.appcheck_v1beta.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.firebase.appcheck_v1beta.types.ListServicesResponse` + 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[..., configuration.ListServicesResponse], + request: configuration.ListServicesRequest, + response: configuration.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.firebase.appcheck_v1beta.types.ListServicesRequest): + The initial request object. + response (google.firebase.appcheck_v1beta.types.ListServicesResponse): + 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 = configuration.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[configuration.ListServicesResponse]: + 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[configuration.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/google/firebase/appcheck_v1beta/services/config_service/transports/__init__.py b/google/firebase/appcheck_v1beta/services/config_service/transports/__init__.py new file mode 100644 index 000000000..390d54e23 --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/config_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ConfigServiceTransport +from .rest import ConfigServiceRestTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceTransport]] +_transport_registry['rest'] = ConfigServiceRestTransport + +__all__ = ( + 'ConfigServiceTransport', + 'ConfigServiceRestTransport', +) diff --git a/google/firebase/appcheck_v1beta/services/config_service/transports/base.py b/google/firebase/appcheck_v1beta/services/config_service/transports/base.py new file mode 100644 index 000000000..dc6c1c2b8 --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/config_service/transports/base.py @@ -0,0 +1,453 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from requests import __version__ as requests_version + +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.firebase.appcheck_v1beta.types import configuration +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-firebase-appcheck', + ).version, + grpc_version=None, + rest_version=requests_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 ConfigServiceTransport(abc.ABC): + """Abstract transport class for ConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', + ) + + DEFAULT_HOST: str = 'firebaseappcheck.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_app_attest_config: gapic_v1.method.wrap_method( + self.get_app_attest_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_app_attest_configs: gapic_v1.method.wrap_method( + self.batch_get_app_attest_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_app_attest_config: gapic_v1.method.wrap_method( + self.update_app_attest_config, + default_timeout=None, + client_info=client_info, + ), + self.get_device_check_config: gapic_v1.method.wrap_method( + self.get_device_check_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_device_check_configs: gapic_v1.method.wrap_method( + self.batch_get_device_check_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_device_check_config: gapic_v1.method.wrap_method( + self.update_device_check_config, + default_timeout=None, + client_info=client_info, + ), + self.get_recaptcha_config: gapic_v1.method.wrap_method( + self.get_recaptcha_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_recaptcha_configs: gapic_v1.method.wrap_method( + self.batch_get_recaptcha_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_recaptcha_config: gapic_v1.method.wrap_method( + self.update_recaptcha_config, + default_timeout=None, + client_info=client_info, + ), + self.get_safety_net_config: gapic_v1.method.wrap_method( + self.get_safety_net_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_safety_net_configs: gapic_v1.method.wrap_method( + self.batch_get_safety_net_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_safety_net_config: gapic_v1.method.wrap_method( + self.update_safety_net_config, + default_timeout=None, + client_info=client_info, + ), + self.get_debug_token: gapic_v1.method.wrap_method( + self.get_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.list_debug_tokens: gapic_v1.method.wrap_method( + self.list_debug_tokens, + default_timeout=None, + client_info=client_info, + ), + self.create_debug_token: gapic_v1.method.wrap_method( + self.create_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.update_debug_token: gapic_v1.method.wrap_method( + self.update_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.delete_debug_token: gapic_v1.method.wrap_method( + self.delete_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_services: gapic_v1.method.wrap_method( + self.batch_update_services, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_app_attest_config(self) -> Callable[ + [configuration.GetAppAttestConfigRequest], + Union[ + configuration.AppAttestConfig, + Awaitable[configuration.AppAttestConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_app_attest_configs(self) -> Callable[ + [configuration.BatchGetAppAttestConfigsRequest], + Union[ + configuration.BatchGetAppAttestConfigsResponse, + Awaitable[configuration.BatchGetAppAttestConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_app_attest_config(self) -> Callable[ + [configuration.UpdateAppAttestConfigRequest], + Union[ + configuration.AppAttestConfig, + Awaitable[configuration.AppAttestConfig] + ]]: + raise NotImplementedError() + + @property + def get_device_check_config(self) -> Callable[ + [configuration.GetDeviceCheckConfigRequest], + Union[ + configuration.DeviceCheckConfig, + Awaitable[configuration.DeviceCheckConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_device_check_configs(self) -> Callable[ + [configuration.BatchGetDeviceCheckConfigsRequest], + Union[ + configuration.BatchGetDeviceCheckConfigsResponse, + Awaitable[configuration.BatchGetDeviceCheckConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_device_check_config(self) -> Callable[ + [configuration.UpdateDeviceCheckConfigRequest], + Union[ + configuration.DeviceCheckConfig, + Awaitable[configuration.DeviceCheckConfig] + ]]: + raise NotImplementedError() + + @property + def get_recaptcha_config(self) -> Callable[ + [configuration.GetRecaptchaConfigRequest], + Union[ + configuration.RecaptchaConfig, + Awaitable[configuration.RecaptchaConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_recaptcha_configs(self) -> Callable[ + [configuration.BatchGetRecaptchaConfigsRequest], + Union[ + configuration.BatchGetRecaptchaConfigsResponse, + Awaitable[configuration.BatchGetRecaptchaConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_recaptcha_config(self) -> Callable[ + [configuration.UpdateRecaptchaConfigRequest], + Union[ + configuration.RecaptchaConfig, + Awaitable[configuration.RecaptchaConfig] + ]]: + raise NotImplementedError() + + @property + def get_safety_net_config(self) -> Callable[ + [configuration.GetSafetyNetConfigRequest], + Union[ + configuration.SafetyNetConfig, + Awaitable[configuration.SafetyNetConfig] + ]]: + raise NotImplementedError() + + @property + def batch_get_safety_net_configs(self) -> Callable[ + [configuration.BatchGetSafetyNetConfigsRequest], + Union[ + configuration.BatchGetSafetyNetConfigsResponse, + Awaitable[configuration.BatchGetSafetyNetConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_safety_net_config(self) -> Callable[ + [configuration.UpdateSafetyNetConfigRequest], + Union[ + configuration.SafetyNetConfig, + Awaitable[configuration.SafetyNetConfig] + ]]: + raise NotImplementedError() + + @property + def get_debug_token(self) -> Callable[ + [configuration.GetDebugTokenRequest], + Union[ + configuration.DebugToken, + Awaitable[configuration.DebugToken] + ]]: + raise NotImplementedError() + + @property + def list_debug_tokens(self) -> Callable[ + [configuration.ListDebugTokensRequest], + Union[ + configuration.ListDebugTokensResponse, + Awaitable[configuration.ListDebugTokensResponse] + ]]: + raise NotImplementedError() + + @property + def create_debug_token(self) -> Callable[ + [configuration.CreateDebugTokenRequest], + Union[ + configuration.DebugToken, + Awaitable[configuration.DebugToken] + ]]: + raise NotImplementedError() + + @property + def update_debug_token(self) -> Callable[ + [configuration.UpdateDebugTokenRequest], + Union[ + configuration.DebugToken, + Awaitable[configuration.DebugToken] + ]]: + raise NotImplementedError() + + @property + def delete_debug_token(self) -> Callable[ + [configuration.DeleteDebugTokenRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [configuration.GetServiceRequest], + Union[ + configuration.Service, + Awaitable[configuration.Service] + ]]: + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [configuration.ListServicesRequest], + Union[ + configuration.ListServicesResponse, + Awaitable[configuration.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [configuration.UpdateServiceRequest], + Union[ + configuration.Service, + Awaitable[configuration.Service] + ]]: + raise NotImplementedError() + + @property + def batch_update_services(self) -> Callable[ + [configuration.BatchUpdateServicesRequest], + Union[ + configuration.BatchUpdateServicesResponse, + Awaitable[configuration.BatchUpdateServicesResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ConfigServiceTransport', +) diff --git a/google/firebase/appcheck_v1beta/services/config_service/transports/rest.py b/google/firebase/appcheck_v1beta/services/config_service/transports/rest.py new file mode 100644 index 000000000..89b48a6c0 --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/config_service/transports/rest.py @@ -0,0 +1,1392 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.firebase.appcheck_v1beta.types import configuration +from google.protobuf import empty_pb2 # type: ignore + +from .base import ConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class ConfigServiceRestTransport(ConfigServiceTransport): + """REST backend transport for ConfigService. + + Manages configuration parameters used by the + [TokenExchangeService][google.firebase.appcheck.v1beta.TokenExchangeService] + and enforcement settings for Firebase services protected by App + Check. + + 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 JSON representations of protocol buffers over HTTP/1.1 + """ + def __init__(self, *, + host: str = 'firebaseappcheck.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = 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. + + 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. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + self._session = AuthorizedSession(self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._prep_wrapped_messages(client_info) + + def get_app_attest_config(self, + request: configuration.GetAppAttestConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Call the get app attest config method over HTTP. + + Args: + request (~.configuration.GetAppAttestConfigRequest): + The request object. Request message for the + [GetAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.GetAppAttestConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.AppAttestConfig: + An app's App Attest configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/appAttestConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.AppAttestConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_app_attest_configs(self, + request: configuration.BatchGetAppAttestConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetAppAttestConfigsResponse: + r"""Call the batch get app attest + configs method over HTTP. + + Args: + request (~.configuration.BatchGetAppAttestConfigsRequest): + The request object. Request message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetAppAttestConfigsResponse: + Response message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/appAttestConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetAppAttestConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_app_attest_config(self, + request: configuration.UpdateAppAttestConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.AppAttestConfig: + r"""Call the update app attest config method over HTTP. + + Args: + request (~.configuration.UpdateAppAttestConfigRequest): + The request object. Request message for the + [UpdateAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateAppAttestConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.AppAttestConfig: + An app's App Attest configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # Jsonify the request body + body = configuration.AppAttestConfig.to_json( + request.app_attest_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app_attest_config.name=projects/*/apps/*/appAttestConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.AppAttestConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_device_check_config(self, + request: configuration.GetDeviceCheckConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Call the get device check config method over HTTP. + + Args: + request (~.configuration.GetDeviceCheckConfigRequest): + The request object. Request message for the + [GetDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.GetDeviceCheckConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DeviceCheckConfig: + An app's DeviceCheck configuration object. This + configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by DeviceCheck. + It also controls certain properties of the returned [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/deviceCheckConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DeviceCheckConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_device_check_configs(self, + request: configuration.BatchGetDeviceCheckConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetDeviceCheckConfigsResponse: + r"""Call the batch get device check + configs method over HTTP. + + Args: + request (~.configuration.BatchGetDeviceCheckConfigsRequest): + The request object. Request message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetDeviceCheckConfigsResponse: + Response message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/deviceCheckConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetDeviceCheckConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_device_check_config(self, + request: configuration.UpdateDeviceCheckConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DeviceCheckConfig: + r"""Call the update device check + config method over HTTP. + + Args: + request (~.configuration.UpdateDeviceCheckConfigRequest): + The request object. Request message for the + [UpdateDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateDeviceCheckConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DeviceCheckConfig: + An app's DeviceCheck configuration object. This + configuration is used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by DeviceCheck. + It also controls certain properties of the returned [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used + as part of the validation process. Please register it + via the Firebase Console or programmatically via the + `Firebase Management + Service `__. + + """ + + # Jsonify the request body + body = configuration.DeviceCheckConfig.to_json( + request.device_check_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{device_check_config.name=projects/*/apps/*/deviceCheckConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DeviceCheckConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_recaptcha_config(self, + request: configuration.GetRecaptchaConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Call the get recaptcha config method over HTTP. + + Args: + request (~.configuration.GetRecaptchaConfigRequest): + The request object. Request message for the + [GetRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.GetRecaptchaConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This + configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by reCAPTCHA + v3. It also controls certain properties of the returned + [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/recaptchaConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.RecaptchaConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_recaptcha_configs(self, + request: configuration.BatchGetRecaptchaConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetRecaptchaConfigsResponse: + r"""Call the batch get recaptcha + configs method over HTTP. + + Args: + request (~.configuration.BatchGetRecaptchaConfigsRequest): + The request object. Request message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetRecaptchaConfigsResponse: + Response message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/recaptchaConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetRecaptchaConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_recaptcha_config(self, + request: configuration.UpdateRecaptchaConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.RecaptchaConfig: + r"""Call the update recaptcha config method over HTTP. + + Args: + request (~.configuration.UpdateRecaptchaConfigRequest): + The request object. Request message for the + [UpdateRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateRecaptchaConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.RecaptchaConfig: + An app's reCAPTCHA v3 configuration object. This + configuration is used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by reCAPTCHA + v3. It also controls certain properties of the returned + [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + """ + + # Jsonify the request body + body = configuration.RecaptchaConfig.to_json( + request.recaptcha_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{recaptcha_config.name=projects/*/apps/*/recaptchaConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.RecaptchaConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_safety_net_config(self, + request: configuration.GetSafetyNetConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Call the get safety net config method over HTTP. + + Args: + request (~.configuration.GetSafetyNetConfigRequest): + The request object. Request message for the + [GetSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.GetSafetyNetConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.SafetyNetConfig: + An app's SafetyNet configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/safetyNetConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.SafetyNetConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_get_safety_net_configs(self, + request: configuration.BatchGetSafetyNetConfigsRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchGetSafetyNetConfigsResponse: + r"""Call the batch get safety net + configs method over HTTP. + + Args: + request (~.configuration.BatchGetSafetyNetConfigsRequest): + The request object. Request message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchGetSafetyNetConfigsResponse: + Response message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/apps/-/safetyNetConfig:batchGet'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['names'] = request.names + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchGetSafetyNetConfigsResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_safety_net_config(self, + request: configuration.UpdateSafetyNetConfigRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.SafetyNetConfig: + r"""Call the update safety net config method over HTTP. + + Args: + request (~.configuration.UpdateSafetyNetConfigRequest): + The request object. Request message for the + [UpdateSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateSafetyNetConfig] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.SafetyNetConfig: + An app's SafetyNet configuration object. This + configuration controls certain properties of the [App + Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate + fingerprints are used to validate tokens issued by + SafetyNet; please register them via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + """ + + # Jsonify the request body + body = configuration.SafetyNetConfig.to_json( + request.safety_net_config, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{safety_net_config.name=projects/*/apps/*/safetyNetConfig}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.SafetyNetConfig.from_json( + response.content, + ignore_unknown_fields=True + ) + + def get_debug_token(self, + request: configuration.GetDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Call the get debug token method over HTTP. + + Args: + request (~.configuration.GetDebugTokenRequest): + The request object. Request message for the + [GetDebugToken][google.firebase.appcheck.v1beta.ConfigService.GetDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DebugToken: + A *debug token* is a secret used during the development + or integration testing of an app. It essentially allows + the development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/debugTokens/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DebugToken.from_json( + response.content, + ignore_unknown_fields=True + ) + + def list_debug_tokens(self, + request: configuration.ListDebugTokensRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.ListDebugTokensResponse: + r"""Call the list debug tokens method over HTTP. + + Args: + request (~.configuration.ListDebugTokensRequest): + The request object. Request message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.ListDebugTokensResponse: + Response message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*/apps/*}/debugTokens'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['pageSize'] = request.page_size + query_params['pageToken'] = request.page_token + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.ListDebugTokensResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def create_debug_token(self, + request: configuration.CreateDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Call the create debug token method over HTTP. + + Args: + request (~.configuration.CreateDebugTokenRequest): + The request object. Request message for the + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DebugToken: + A *debug token* is a secret used during the development + or integration testing of an app. It essentially allows + the development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + + # Jsonify the request body + body = configuration.DebugToken.to_json( + request.debug_token, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*/apps/*}/debugTokens'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DebugToken.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_debug_token(self, + request: configuration.UpdateDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.DebugToken: + r"""Call the update debug token method over HTTP. + + Args: + request (~.configuration.UpdateDebugTokenRequest): + The request object. Request message for the + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.DebugToken: + A *debug token* is a secret used during the development + or integration testing of an app. It essentially allows + the development or integration testing to bypass app + attestation while still allowing App Check to enforce + protection on supported production Firebase services. + + """ + + # Jsonify the request body + body = configuration.DebugToken.to_json( + request.debug_token, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{debug_token.name=projects/*/apps/*/debugTokens/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.DebugToken.from_json( + response.content, + ignore_unknown_fields=True + ) + + def delete_debug_token(self, + request: configuration.DeleteDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> empty_pb2.Empty: + r"""Call the delete debug token method over HTTP. + + Args: + request (~.configuration.DeleteDebugTokenRequest): + The request object. Request message for the + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/apps/*/debugTokens/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.delete( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + def get_service(self, + request: configuration.GetServiceRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Call the get service method over HTTP. + + Args: + request (~.configuration.GetServiceRequest): + The request object. Request message for the + [GetService][google.firebase.appcheck.v1beta.ConfigService.GetService] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=projects/*/services/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.Service.from_json( + response.content, + ignore_unknown_fields=True + ) + + def list_services(self, + request: configuration.ListServicesRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.configuration.ListServicesRequest): + The request object. Request message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.ListServicesResponse: + Response message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/services'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['pageSize'] = request.page_size + query_params['pageToken'] = request.page_token + query_params['parent'] = request.parent + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.ListServicesResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def update_service(self, + request: configuration.UpdateServiceRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.Service: + r"""Call the update service method over HTTP. + + Args: + request (~.configuration.UpdateServiceRequest): + The request object. Request message for the + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + method as well as an individual update message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.Service: + The enforcement configuration for a + Firebase service supported by App Check. + + """ + + # Jsonify the request body + body = configuration.Service.to_json( + request.service, + including_default_value_fields=False, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{service.name=projects/*/services/*}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.patch( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.Service.from_json( + response.content, + ignore_unknown_fields=True + ) + + def batch_update_services(self, + request: configuration.BatchUpdateServicesRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> configuration.BatchUpdateServicesResponse: + r"""Call the batch update services method over HTTP. + + Args: + request (~.configuration.BatchUpdateServicesRequest): + The request object. Request message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.configuration.BatchUpdateServicesResponse: + Response message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + """ + + # Jsonify the request body + body = configuration.BatchUpdateServicesRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{parent=projects/*}/services:batchUpdate'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['parent'] = request.parent + query_params['requests'] = request.requests + query_params['updateMask'] = request.update_mask + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return configuration.BatchUpdateServicesResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + +__all__ = ( + 'ConfigServiceRestTransport', +) diff --git a/google/firebase/appcheck_v1beta/services/token_exchange_service/__init__.py b/google/firebase/appcheck_v1beta/services/token_exchange_service/__init__.py new file mode 100644 index 000000000..41feb8785 --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/token_exchange_service/__init__.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TokenExchangeServiceClient + +__all__ = ( + 'TokenExchangeServiceClient', +) diff --git a/google/firebase/appcheck_v1beta/services/token_exchange_service/client.py b/google/firebase/appcheck_v1beta/services/token_exchange_service/client.py new file mode 100644 index 000000000..5e78359ea --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/token_exchange_service/client.py @@ -0,0 +1,917 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.firebase.appcheck_v1beta.types import token_exchange_service +from google.protobuf import duration_pb2 # type: ignore +from .transports.base import TokenExchangeServiceTransport, DEFAULT_CLIENT_INFO +from .transports.rest import TokenExchangeServiceRestTransport + + +class TokenExchangeServiceClientMeta(type): + """Metaclass for the TokenExchangeService 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[TokenExchangeServiceTransport]] + _transport_registry["rest"] = TokenExchangeServiceRestTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TokenExchangeServiceTransport]: + """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 TokenExchangeServiceClient(metaclass=TokenExchangeServiceClientMeta): + """A service to validate certification material issued to apps by app + or device attestation providers, and exchange them for *App Check + tokens* (see + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]), + used to access Firebase services protected by App Check. + """ + + @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 = "firebaseappcheck.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: + TokenExchangeServiceClient: 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: + TokenExchangeServiceClient: 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) -> TokenExchangeServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TokenExchangeServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def public_jwk_set_path() -> str: + """Returns a fully-qualified public_jwk_set string.""" + return "jwks".format() + + @staticmethod + def parse_public_jwk_set_path(path: str) -> Dict[str,str]: + """Parses a public_jwk_set path into its component segments.""" + m = re.match(r"^jwks$", 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, TokenExchangeServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the token exchange service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TokenExchangeServiceTransport]): 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, TokenExchangeServiceTransport): + # transport is a TokenExchangeServiceTransport 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, + ) + + def get_public_jwk_set(self, + request: token_exchange_service.GetPublicJwkSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.PublicJwkSet: + r"""Returns a public JWK set as specified by `RFC + 7517 `__ that can be used + to verify App Check tokens. Exactly one of the public keys in + the returned set will successfully validate any App Check token + that is currently valid. + + Args: + request (google.firebase.appcheck_v1beta.types.GetPublicJwkSetRequest): + The request object. Request message for the + [GetPublicJwkSet][] method. + name (str): + Required. The relative resource name to the public JWK + set. Must always be exactly the string ``jwks``. + + 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.firebase.appcheck_v1beta.types.PublicJwkSet: + The currently active set of public keys that can be used to verify App Check + tokens. + + This object is a JWK set as specified by [section 5 + of RFC + 7517](\ https://tools.ietf.org/html/rfc7517#section-5). + + For security, the response **must not** be cached for + longer than one day. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 token_exchange_service.GetPublicJwkSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.GetPublicJwkSetRequest): + request = token_exchange_service.GetPublicJwkSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_public_jwk_set] + + # Certain fields should be 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 exchange_safety_net_token(self, + request: token_exchange_service.ExchangeSafetyNetTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a `SafetyNet + token `__. + If valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeSafetyNetTokenRequest): + The request object. Request message for the + [ExchangeSafetyNetToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeSafetyNetTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeSafetyNetTokenRequest): + request = token_exchange_service.ExchangeSafetyNetTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_safety_net_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_device_check_token(self, + request: token_exchange_service.ExchangeDeviceCheckTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Accepts a + ```device_token`` `__ + issued by DeviceCheck, and attempts to validate it with Apple. + If valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeDeviceCheckTokenRequest): + The request object. Request message for the + [ExchangeDeviceCheckToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeDeviceCheckTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeDeviceCheckTokenRequest): + request = token_exchange_service.ExchangeDeviceCheckTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_device_check_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_recaptcha_token(self, + request: token_exchange_service.ExchangeRecaptchaTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a `reCAPTCHA v3 response + token `__. If + valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeRecaptchaTokenRequest): + The request object. Request message for the + [ExchangeRecaptchaToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeRecaptchaTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeRecaptchaTokenRequest): + request = token_exchange_service.ExchangeRecaptchaTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_recaptcha_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_custom_token(self, + request: token_exchange_service.ExchangeCustomTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a custom token signed using your project's Admin SDK + service account credentials. If valid, returns an App Check + token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeCustomTokenRequest): + The request object. Request message for the + [ExchangeCustomToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeCustomTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeCustomTokenRequest): + request = token_exchange_service.ExchangeCustomTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_custom_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_debug_token(self, + request: token_exchange_service.ExchangeDebugTokenRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Validates a debug token secret that you have previously created + using + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken]. + If valid, returns an App Check token encapsulated in an + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]. + + Note that a restrictive quota is enforced on this method to + prevent accidental exposure of the app to abuse. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeDebugTokenRequest): + The request object. Request message for the + [ExchangeDebugToken][] 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.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeDebugTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeDebugTokenRequest): + request = token_exchange_service.ExchangeDebugTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_debug_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_app_attest_challenge(self, + request: token_exchange_service.GenerateAppAttestChallengeRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AppAttestChallengeResponse: + r"""Initiates the App Attest flow by generating a + challenge which will be used as a type of nonce for this + attestation. + + Args: + request (google.firebase.appcheck_v1beta.types.GenerateAppAttestChallengeRequest): + The request object. Request message for + GenerateAppAttestChallenge + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.AppAttestChallengeResponse: + Response object for + GenerateAppAttestChallenge + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.GenerateAppAttestChallengeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.GenerateAppAttestChallengeRequest): + request = token_exchange_service.GenerateAppAttestChallengeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_app_attest_challenge] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_app_attest_attestation(self, + request: token_exchange_service.ExchangeAppAttestAttestationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.ExchangeAppAttestAttestationResponse: + r"""Accepts a AppAttest CBOR Attestation, and uses the + developer's preconfigured team and bundle IDs to verify + the token with Apple. Returns an Attestation Artifact + that can later be exchanged for an AttestationToken in + ExchangeAppAttestAssertion. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeAppAttestAttestationRequest): + The request object. Request message for + ExchangeAppAttestAttestation + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.ExchangeAppAttestAttestationResponse: + Response message for + ExchangeAppAttestAttestation and + ExchangeAppAttestDebugAttestation + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeAppAttestAttestationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeAppAttestAttestationRequest): + request = token_exchange_service.ExchangeAppAttestAttestationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_app_attest_attestation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def exchange_app_attest_assertion(self, + request: token_exchange_service.ExchangeAppAttestAssertionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Accepts a AppAttest Artifact and Assertion, and uses the + developer's preconfigured auth token to verify the token with + Apple. Returns an AttestationToken with the App ID as specified + by the ``app`` field included as attested claims. + + Args: + request (google.firebase.appcheck_v1beta.types.ExchangeAppAttestAssertionRequest): + The request object. Request message for + ExchangeAppAttestAssertion + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.firebase.appcheck_v1beta.types.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to access Firebase services + protected by App Check. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a token_exchange_service.ExchangeAppAttestAssertionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, token_exchange_service.ExchangeAppAttestAssertionRequest): + request = token_exchange_service.ExchangeAppAttestAssertionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.exchange_app_attest_assertion] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("app", request.app), + )), + ) + + # 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-firebase-appcheck", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TokenExchangeServiceClient", +) diff --git a/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/__init__.py b/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/__init__.py new file mode 100644 index 000000000..d0f63506a --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TokenExchangeServiceTransport +from .rest import TokenExchangeServiceRestTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TokenExchangeServiceTransport]] +_transport_registry['rest'] = TokenExchangeServiceRestTransport + +__all__ = ( + 'TokenExchangeServiceTransport', + 'TokenExchangeServiceRestTransport', +) diff --git a/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/base.py b/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/base.py new file mode 100644 index 000000000..3576d9456 --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/base.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from requests import __version__ as requests_version + +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.firebase.appcheck_v1beta.types import token_exchange_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-firebase-appcheck', + ).version, + grpc_version=None, + rest_version=requests_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 TokenExchangeServiceTransport(abc.ABC): + """Abstract transport class for TokenExchangeService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/firebase', + ) + + DEFAULT_HOST: str = 'firebaseappcheck.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_public_jwk_set: gapic_v1.method.wrap_method( + self.get_public_jwk_set, + default_timeout=None, + client_info=client_info, + ), + self.exchange_safety_net_token: gapic_v1.method.wrap_method( + self.exchange_safety_net_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_device_check_token: gapic_v1.method.wrap_method( + self.exchange_device_check_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_recaptcha_token: gapic_v1.method.wrap_method( + self.exchange_recaptcha_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_custom_token: gapic_v1.method.wrap_method( + self.exchange_custom_token, + default_timeout=None, + client_info=client_info, + ), + self.exchange_debug_token: gapic_v1.method.wrap_method( + self.exchange_debug_token, + default_timeout=None, + client_info=client_info, + ), + self.generate_app_attest_challenge: gapic_v1.method.wrap_method( + self.generate_app_attest_challenge, + default_timeout=None, + client_info=client_info, + ), + self.exchange_app_attest_attestation: gapic_v1.method.wrap_method( + self.exchange_app_attest_attestation, + default_timeout=None, + client_info=client_info, + ), + self.exchange_app_attest_assertion: gapic_v1.method.wrap_method( + self.exchange_app_attest_assertion, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_public_jwk_set(self) -> Callable[ + [token_exchange_service.GetPublicJwkSetRequest], + Union[ + token_exchange_service.PublicJwkSet, + Awaitable[token_exchange_service.PublicJwkSet] + ]]: + raise NotImplementedError() + + @property + def exchange_safety_net_token(self) -> Callable[ + [token_exchange_service.ExchangeSafetyNetTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_device_check_token(self) -> Callable[ + [token_exchange_service.ExchangeDeviceCheckTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_recaptcha_token(self) -> Callable[ + [token_exchange_service.ExchangeRecaptchaTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_custom_token(self) -> Callable[ + [token_exchange_service.ExchangeCustomTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_debug_token(self) -> Callable[ + [token_exchange_service.ExchangeDebugTokenRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + @property + def generate_app_attest_challenge(self) -> Callable[ + [token_exchange_service.GenerateAppAttestChallengeRequest], + Union[ + token_exchange_service.AppAttestChallengeResponse, + Awaitable[token_exchange_service.AppAttestChallengeResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_app_attest_attestation(self) -> Callable[ + [token_exchange_service.ExchangeAppAttestAttestationRequest], + Union[ + token_exchange_service.ExchangeAppAttestAttestationResponse, + Awaitable[token_exchange_service.ExchangeAppAttestAttestationResponse] + ]]: + raise NotImplementedError() + + @property + def exchange_app_attest_assertion(self) -> Callable[ + [token_exchange_service.ExchangeAppAttestAssertionRequest], + Union[ + token_exchange_service.AttestationTokenResponse, + Awaitable[token_exchange_service.AttestationTokenResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TokenExchangeServiceTransport', +) diff --git a/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/rest.py b/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/rest.py new file mode 100644 index 000000000..26c856566 --- /dev/null +++ b/google/firebase/appcheck_v1beta/services/token_exchange_service/transports/rest.py @@ -0,0 +1,644 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.firebase.appcheck_v1beta.types import token_exchange_service + +from .base import TokenExchangeServiceTransport, DEFAULT_CLIENT_INFO + + +class TokenExchangeServiceRestTransport(TokenExchangeServiceTransport): + """REST backend transport for TokenExchangeService. + + A service to validate certification material issued to apps by app + or device attestation providers, and exchange them for *App Check + tokens* (see + [AttestationTokenResponse][google.firebase.appcheck.v1beta.AttestationTokenResponse]), + used to access Firebase services protected by App Check. + + 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 JSON representations of protocol buffers over HTTP/1.1 + """ + def __init__(self, *, + host: str = 'firebaseappcheck.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = 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. + + 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. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + self._session = AuthorizedSession(self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._prep_wrapped_messages(client_info) + + def get_public_jwk_set(self, + request: token_exchange_service.GetPublicJwkSetRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.PublicJwkSet: + r"""Call the get public jwk set method over HTTP. + + Args: + request (~.token_exchange_service.GetPublicJwkSetRequest): + The request object. Request message for the [GetPublicJwkSet][] method. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.PublicJwkSet: + The currently active set of public keys that can be used + to verify App Check tokens. + + This object is a JWK set as specified by `section 5 of + RFC + 7517 `__. + + For security, the response **must not** be cached for + longer than one day. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{name=jwks}'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['name'] = request.name + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.get( + url, + headers=headers, + params=query_params, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.PublicJwkSet.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_safety_net_token(self, + request: token_exchange_service.ExchangeSafetyNetTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange safety net token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeSafetyNetTokenRequest): + The request object. Request message for the [ExchangeSafetyNetToken][] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeSafetyNetTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeSafetyNetToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['safetyNetToken'] = request.safety_net_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_device_check_token(self, + request: token_exchange_service.ExchangeDeviceCheckTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange device check + token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeDeviceCheckTokenRequest): + The request object. Request message for the [ExchangeDeviceCheckToken][] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeDeviceCheckTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeDeviceCheckToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['deviceToken'] = request.device_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_recaptcha_token(self, + request: token_exchange_service.ExchangeRecaptchaTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange recaptcha token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeRecaptchaTokenRequest): + The request object. Request message for the [ExchangeRecaptchaToken][] + method. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeRecaptchaTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeRecaptchaToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['recaptchaToken'] = request.recaptcha_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_custom_token(self, + request: token_exchange_service.ExchangeCustomTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange custom token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeCustomTokenRequest): + The request object. Request message for the [ExchangeCustomToken][] method. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeCustomTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app}:exchangeCustomToken'.format( + host=self._host, app=request.app + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['customToken'] = request.custom_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_debug_token(self, + request: token_exchange_service.ExchangeDebugTokenRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange debug token method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeDebugTokenRequest): + The request object. Request message for the [ExchangeDebugToken][] method. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeDebugTokenRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeDebugToken'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['debugToken'] = request.debug_token + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def generate_app_attest_challenge(self, + request: token_exchange_service.GenerateAppAttestChallengeRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AppAttestChallengeResponse: + r"""Call the generate app attest + challenge method over HTTP. + + Args: + request (~.token_exchange_service.GenerateAppAttestChallengeRequest): + The request object. Request message for + GenerateAppAttestChallenge + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AppAttestChallengeResponse: + Response object for + GenerateAppAttestChallenge + + """ + + # Jsonify the request body + body = token_exchange_service.GenerateAppAttestChallengeRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:generateAppAttestChallenge'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AppAttestChallengeResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_app_attest_attestation(self, + request: token_exchange_service.ExchangeAppAttestAttestationRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.ExchangeAppAttestAttestationResponse: + r"""Call the exchange app attest + attestation method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeAppAttestAttestationRequest): + The request object. Request message for + ExchangeAppAttestAttestation + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.ExchangeAppAttestAttestationResponse: + Response message for + ExchangeAppAttestAttestation and + ExchangeAppAttestDebugAttestation + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeAppAttestAttestationRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeAppAttestAttestation'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['attestationStatement'] = request.attestation_statement + query_params['challenge'] = request.challenge + query_params['keyId'] = request.key_id + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.ExchangeAppAttestAttestationResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + def exchange_app_attest_assertion(self, + request: token_exchange_service.ExchangeAppAttestAssertionRequest, *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> token_exchange_service.AttestationTokenResponse: + r"""Call the exchange app attest + assertion method over HTTP. + + Args: + request (~.token_exchange_service.ExchangeAppAttestAssertionRequest): + The request object. Request message for + ExchangeAppAttestAssertion + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.token_exchange_service.AttestationTokenResponse: + Encapsulates an *App Check token*, which are used to + access Firebase services protected by App Check. + + """ + + # Jsonify the request body + body = token_exchange_service.ExchangeAppAttestAssertionRequest.to_json( + request, + use_integers_for_enums=False + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = 'https://{host}/v1beta/{app=projects/*/apps/*}:exchangeAppAttestAssertion'.format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + query_params['app'] = request.app + query_params['artifact'] = request.artifact + query_params['assertion'] = request.assertion + query_params['challenge'] = request.challenge + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = self._session.post( + url, + headers=headers, + params=query_params, + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + return token_exchange_service.AttestationTokenResponse.from_json( + response.content, + ignore_unknown_fields=True + ) + + +__all__ = ( + 'TokenExchangeServiceRestTransport', +) diff --git a/google/firebase/appcheck_v1beta/types/__init__.py b/google/firebase/appcheck_v1beta/types/__init__.py new file mode 100644 index 000000000..fce4e042a --- /dev/null +++ b/google/firebase/appcheck_v1beta/types/__init__.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .configuration import ( + AppAttestConfig, + BatchGetAppAttestConfigsRequest, + BatchGetAppAttestConfigsResponse, + BatchGetDeviceCheckConfigsRequest, + BatchGetDeviceCheckConfigsResponse, + BatchGetRecaptchaConfigsRequest, + BatchGetRecaptchaConfigsResponse, + BatchGetSafetyNetConfigsRequest, + BatchGetSafetyNetConfigsResponse, + BatchUpdateServicesRequest, + BatchUpdateServicesResponse, + CreateDebugTokenRequest, + DebugToken, + DeleteDebugTokenRequest, + DeviceCheckConfig, + GetAppAttestConfigRequest, + GetDebugTokenRequest, + GetDeviceCheckConfigRequest, + GetRecaptchaConfigRequest, + GetSafetyNetConfigRequest, + GetServiceRequest, + ListDebugTokensRequest, + ListDebugTokensResponse, + ListServicesRequest, + ListServicesResponse, + RecaptchaConfig, + SafetyNetConfig, + Service, + UpdateAppAttestConfigRequest, + UpdateDebugTokenRequest, + UpdateDeviceCheckConfigRequest, + UpdateRecaptchaConfigRequest, + UpdateSafetyNetConfigRequest, + UpdateServiceRequest, +) +from .token_exchange_service import ( + AppAttestChallengeResponse, + AttestationTokenResponse, + ExchangeAppAttestAssertionRequest, + ExchangeAppAttestAttestationRequest, + ExchangeAppAttestAttestationResponse, + ExchangeCustomTokenRequest, + ExchangeDebugTokenRequest, + ExchangeDeviceCheckTokenRequest, + ExchangeRecaptchaTokenRequest, + ExchangeSafetyNetTokenRequest, + GenerateAppAttestChallengeRequest, + GetPublicJwkSetRequest, + PublicJwk, + PublicJwkSet, +) + +__all__ = ( + 'AppAttestConfig', + 'BatchGetAppAttestConfigsRequest', + 'BatchGetAppAttestConfigsResponse', + 'BatchGetDeviceCheckConfigsRequest', + 'BatchGetDeviceCheckConfigsResponse', + 'BatchGetRecaptchaConfigsRequest', + 'BatchGetRecaptchaConfigsResponse', + 'BatchGetSafetyNetConfigsRequest', + 'BatchGetSafetyNetConfigsResponse', + 'BatchUpdateServicesRequest', + 'BatchUpdateServicesResponse', + 'CreateDebugTokenRequest', + 'DebugToken', + 'DeleteDebugTokenRequest', + 'DeviceCheckConfig', + 'GetAppAttestConfigRequest', + 'GetDebugTokenRequest', + 'GetDeviceCheckConfigRequest', + 'GetRecaptchaConfigRequest', + 'GetSafetyNetConfigRequest', + 'GetServiceRequest', + 'ListDebugTokensRequest', + 'ListDebugTokensResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'RecaptchaConfig', + 'SafetyNetConfig', + 'Service', + 'UpdateAppAttestConfigRequest', + 'UpdateDebugTokenRequest', + 'UpdateDeviceCheckConfigRequest', + 'UpdateRecaptchaConfigRequest', + 'UpdateSafetyNetConfigRequest', + 'UpdateServiceRequest', + 'AppAttestChallengeResponse', + 'AttestationTokenResponse', + 'ExchangeAppAttestAssertionRequest', + 'ExchangeAppAttestAttestationRequest', + 'ExchangeAppAttestAttestationResponse', + 'ExchangeCustomTokenRequest', + 'ExchangeDebugTokenRequest', + 'ExchangeDeviceCheckTokenRequest', + 'ExchangeRecaptchaTokenRequest', + 'ExchangeSafetyNetTokenRequest', + 'GenerateAppAttestChallengeRequest', + 'GetPublicJwkSetRequest', + 'PublicJwk', + 'PublicJwkSet', +) diff --git a/google/firebase/appcheck_v1beta/types/config_service.py b/google/firebase/appcheck_v1beta/types/config_service.py new file mode 100644 index 000000000..a4b1757d1 --- /dev/null +++ b/google/firebase/appcheck_v1beta/types/config_service.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.firebase.appcheck.v1beta', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/firebase/appcheck_v1beta/types/configuration.py b/google/firebase/appcheck_v1beta/types/configuration.py new file mode 100644 index 000000000..ae1904a4c --- /dev/null +++ b/google/firebase/appcheck_v1beta/types/configuration.py @@ -0,0 +1,1277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.firebase.appcheck.v1beta', + manifest={ + 'AppAttestConfig', + 'GetAppAttestConfigRequest', + 'BatchGetAppAttestConfigsRequest', + 'BatchGetAppAttestConfigsResponse', + 'UpdateAppAttestConfigRequest', + 'DeviceCheckConfig', + 'GetDeviceCheckConfigRequest', + 'BatchGetDeviceCheckConfigsRequest', + 'BatchGetDeviceCheckConfigsResponse', + 'UpdateDeviceCheckConfigRequest', + 'RecaptchaConfig', + 'GetRecaptchaConfigRequest', + 'BatchGetRecaptchaConfigsRequest', + 'BatchGetRecaptchaConfigsResponse', + 'UpdateRecaptchaConfigRequest', + 'SafetyNetConfig', + 'GetSafetyNetConfigRequest', + 'BatchGetSafetyNetConfigsRequest', + 'BatchGetSafetyNetConfigsResponse', + 'UpdateSafetyNetConfigRequest', + 'DebugToken', + 'GetDebugTokenRequest', + 'ListDebugTokensRequest', + 'ListDebugTokensResponse', + 'CreateDebugTokenRequest', + 'UpdateDebugTokenRequest', + 'DeleteDebugTokenRequest', + 'Service', + 'GetServiceRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'UpdateServiceRequest', + 'BatchUpdateServicesRequest', + 'BatchUpdateServicesResponse', + }, +) + + +class AppAttestConfig(proto.Message): + r"""An app's App Attest configuration object. This configuration + controls certain properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAttestation] + and + [ExchangeAppAttestAttestation][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeAppAttestAssertion], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used as part of + the validation process. Please register it via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + Attributes: + name (str): + Required. The relative resource name of the App Attest + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from App Attest artifacts will + be valid. If unset, a default value of 1 hour is + assumed. Must be between 30 minutes and 7 days, + inclusive. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + token_ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class GetAppAttestConfigRequest(proto.Message): + r"""Request message for the + [GetAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.GetAppAttestConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetAppAttestConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + to retrieve, in the format + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetAppAttestConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetAppAttestConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetAppAttestConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.AppAttestConfig]): + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AppAttestConfig', + ) + + +class UpdateAppAttestConfigRequest(proto.Message): + r"""Request message for the + [UpdateAppAttestConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateAppAttestConfig] + method. + + Attributes: + app_attest_config (google.firebase.appcheck_v1beta.types.AppAttestConfig): + Required. The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + to update. + + The + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/appAttestConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [AppAttestConfig][google.firebase.appcheck.v1beta.AppAttestConfig] + Gets to update. Example: ``token_ttl``. + """ + + app_attest_config = proto.Field( + proto.MESSAGE, + number=1, + message='AppAttestConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeviceCheckConfig(proto.Message): + r"""An app's DeviceCheck configuration object. This configuration is + used by + [ExchangeDeviceCheckToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken] + to validate device tokens issued to apps by DeviceCheck. It also + controls certain properties of the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that the Team ID registered with your app is used as part of + the validation process. Please register it via the Firebase Console + or programmatically via the `Firebase Management + Service `__. + + Attributes: + name (str): + Required. The relative resource name of the DeviceCheck + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from DeviceCheck tokens will be + valid. If unset, a default value of 1 hour is + assumed. Must be between 30 minutes and 7 days, + inclusive. + key_id (str): + Required. The key identifier of a private key + enabled with DeviceCheck, created in your Apple + Developer account. + private_key (str): + Required. Input only. The contents of the private key + (``.p8``) file associated with the key specified by + ``key_id``. + + For security reasons, this field will never be populated in + any response. + private_key_set (bool): + Output only. Whether the ``private_key`` field was + previously set. Since we will never return the + ``private_key`` field, this field is the only way to find + out whether it was previously set. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + token_ttl = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + key_id = proto.Field( + proto.STRING, + number=2, + ) + private_key = proto.Field( + proto.STRING, + number=3, + ) + private_key_set = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDeviceCheckConfigRequest(proto.Message): + r"""Request message for the + [GetDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.GetDeviceCheckConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetDeviceCheckConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + to retrieve, in the format + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetDeviceCheckConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetDeviceCheckConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetDeviceCheckConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.DeviceCheckConfig]): + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DeviceCheckConfig', + ) + + +class UpdateDeviceCheckConfigRequest(proto.Message): + r"""Request message for the + [UpdateDeviceCheckConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateDeviceCheckConfig] + method. + + Attributes: + device_check_config (google.firebase.appcheck_v1beta.types.DeviceCheckConfig): + Required. The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + to update. + + The + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/deviceCheckConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [DeviceCheckConfig][google.firebase.appcheck.v1beta.DeviceCheckConfig] + Gets to update. Example: ``key_id,private_key``. + """ + + device_check_config = proto.Field( + proto.MESSAGE, + number=1, + message='DeviceCheckConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class RecaptchaConfig(proto.Message): + r"""An app's reCAPTCHA v3 configuration object. This configuration is + used by + [ExchangeRecaptchaToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeRecaptchaToken] + to validate reCAPTCHA tokens issued to apps by reCAPTCHA v3. It also + controls certain properties of the returned [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Attributes: + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from reCAPTCHA tokens will be + valid. If unset, a default value of 1 day is + assumed. Must be between 30 minutes and 7 days, + inclusive. + name (str): + Required. The relative resource name of the reCAPTCHA v3 + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + site_secret (str): + Required. Input only. The site secret used to + identify your service for reCAPTCHA v3 + verification. + For security reasons, this field will never be + populated in any response. + site_secret_set (bool): + Output only. Whether the ``site_secret`` field was + previously set. Since we will never return the + ``site_secret`` field, this field is the only way to find + out whether it was previously set. + """ + + token_ttl = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + site_secret = proto.Field( + proto.STRING, + number=2, + ) + site_secret_set = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetRecaptchaConfigRequest(proto.Message): + r"""Request message for the + [GetRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.GetRecaptchaConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetRecaptchaConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + to retrieve, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetRecaptchaConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetRecaptchaConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetRecaptchaConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.RecaptchaConfig]): + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RecaptchaConfig', + ) + + +class UpdateRecaptchaConfigRequest(proto.Message): + r"""Request message for the + [UpdateRecaptchaConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateRecaptchaConfig] + method. + + Attributes: + recaptcha_config (google.firebase.appcheck_v1beta.types.RecaptchaConfig): + Required. The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. + + The + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/recaptchaConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [RecaptchaConfig][google.firebase.appcheck.v1beta.RecaptchaConfig] + to update. Example: ``site_secret``. + """ + + recaptcha_config = proto.Field( + proto.MESSAGE, + number=1, + message='RecaptchaConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SafetyNetConfig(proto.Message): + r"""An app's SafetyNet configuration object. This configuration controls + certain properties of the [App Check + token][google.firebase.appcheck.v1beta.AttestationTokenResponse] + returned by + [ExchangeSafetyNetToken][google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeSafetyNetToken], + such as its + [ttl][google.firebase.appcheck.v1beta.AttestationTokenResponse.ttl]. + + Note that your registered SHA-256 certificate fingerprints are used + to validate tokens issued by SafetyNet; please register them via the + Firebase Console or programmatically via the `Firebase Management + Service `__. + + Attributes: + name (str): + Required. The relative resource name of the SafetyNet + configuration object, in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + token_ttl (google.protobuf.duration_pb2.Duration): + Specifies the duration for which App Check + tokens exchanged from SafetyNet tokens will be + valid. If unset, a default value of 1 hour is + assumed. Must be between 30 minutes and 7 days, + inclusive. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + token_ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class GetSafetyNetConfigRequest(proto.Message): + r"""Request message for the + [GetSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.GetSafetyNetConfig] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig], + in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetSafetyNetConfigsRequest(proto.Message): + r"""Request message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + being retrieved, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being retrieved must match this field, or the entire batch + fails. + names (Sequence[str]): + Required. The relative resource names of the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + to retrieve, in the format + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + + A maximum of 100 objects can be retrieved in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetSafetyNetConfigsResponse(proto.Message): + r"""Response message for the + [BatchGetSafetyNetConfigs][google.firebase.appcheck.v1beta.ConfigService.BatchGetSafetyNetConfigs] + method. + + Attributes: + configs (Sequence[google.firebase.appcheck_v1beta.types.SafetyNetConfig]): + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]s + retrieved. + """ + + configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SafetyNetConfig', + ) + + +class UpdateSafetyNetConfigRequest(proto.Message): + r"""Request message for the + [UpdateSafetyNetConfig][google.firebase.appcheck.v1beta.ConfigService.UpdateSafetyNetConfig] + method. + + Attributes: + safety_net_config (google.firebase.appcheck_v1beta.types.SafetyNetConfig): + Required. The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + to update. + + The + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig]'s + ``name`` field is used to identify the configuration to be + updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/safetyNetConfig + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [SafetyNetConfig][google.firebase.appcheck.v1beta.SafetyNetConfig] + Gets to update. Example: ``token_ttl``. + """ + + safety_net_config = proto.Field( + proto.MESSAGE, + number=1, + message='SafetyNetConfig', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DebugToken(proto.Message): + r"""A *debug token* is a secret used during the development or + integration testing of an app. It essentially allows the development + or integration testing to bypass app attestation while still + allowing App Check to enforce protection on supported production + Firebase services. + + Attributes: + name (str): + The relative resource name of the debug token, in the + format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + display_name (str): + Required. A human readable display name used + to identify this debug token. + token (str): + Input only. Immutable. The secret token itself. Must be + provided during creation, and must be a UUID4, case + insensitive. + + This field is immutable once set, and cannot be provided + during an + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + request. You can, however, delete this debug token using + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + to revoke it. + + For security reasons, this field will never be populated in + any response. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + token = proto.Field( + proto.STRING, + number=3, + ) + + +class GetDebugTokenRequest(proto.Message): + r"""Request message for the + [GetDebugToken][google.firebase.appcheck.v1beta.ConfigService.GetDebugToken] + method. + + Attributes: + name (str): + Required. The relative resource name of the debug token, in + the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDebugTokensRequest(proto.Message): + r"""Request message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + Attributes: + parent (str): + Required. The relative resource name of the parent app for + which to list each associated + [DebugToken][google.firebase.appcheck.v1beta.DebugToken], in + the format: + + :: + + projects/{project_number}/apps/{app_id} + page_size (int): + The maximum number of + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s to + return in the response. Note that an app can have at most 20 + debug tokens. + + The server may return fewer than this at its own discretion. + If no value is specified (or too large a value is + specified), the server will impose its own limit. + page_token (str): + Token returned from a previous call to + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + indicating where in the set of + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s to + resume listing. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + must match the call that provided the page token; if they do + not match, the result is undefined. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDebugTokensResponse(proto.Message): + r"""Response message for the + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + method. + + Attributes: + debug_tokens (Sequence[google.firebase.appcheck_v1beta.types.DebugToken]): + The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s + retrieved. + next_page_token (str): + If the result list is too large to fit in a single response, + then a token is returned. If the string is empty or omitted, + then this response is the last page of results. + + This token can be used in a subsequent call to + [ListDebugTokens][google.firebase.appcheck.v1beta.ConfigService.ListDebugTokens] + to find the next group of + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]s. + + Page tokens are short-lived and should not be persisted. + """ + + @property + def raw_page(self): + return self + + debug_tokens = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='DebugToken', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDebugTokenRequest(proto.Message): + r"""Request message for the + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken] + method. + + Attributes: + parent (str): + Required. The relative resource name of the parent app in + which the specified + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will be created, in the format: + + :: + + projects/{project_number}/apps/{app_id} + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + create. + + For security reasons, after creation, the ``token`` field of + the [DebugToken][google.firebase.appcheck.v1beta.DebugToken] + will never be populated in any response. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + debug_token = proto.Field( + proto.MESSAGE, + number=2, + message='DebugToken', + ) + + +class UpdateDebugTokenRequest(proto.Message): + r"""Request message for the + [UpdateDebugToken][google.firebase.appcheck.v1beta.ConfigService.UpdateDebugToken] + method. + + Attributes: + debug_token (google.firebase.appcheck_v1beta.types.DebugToken): + Required. The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + update. + + The + [DebugToken][google.firebase.appcheck.v1beta.DebugToken]'s + ``name`` field is used to identify the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + be updated, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + update. Example: ``display_name``. + """ + + debug_token = proto.Field( + proto.MESSAGE, + number=1, + message='DebugToken', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDebugTokenRequest(proto.Message): + r"""Request message for the + [DeleteDebugToken][google.firebase.appcheck.v1beta.ConfigService.DeleteDebugToken] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [DebugToken][google.firebase.appcheck.v1beta.DebugToken] to + delete, in the format: + + :: + + projects/{project_number}/apps/{app_id}/debugTokens/{debug_token_id} + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class Service(proto.Message): + r"""The enforcement configuration for a Firebase service + supported by App Check. + + Attributes: + name (str): + Required. The relative resource name of the service + configuration object, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase Realtime + Database) + enforcement_mode (google.firebase.appcheck_v1beta.types.Service.EnforcementMode): + Required. The App Check enforcement mode for + this service. + """ + class EnforcementMode(proto.Enum): + r"""The App Check enforcement mode for a Firebase service + supported by App Check. + """ + OFF = 0 + UNENFORCED = 1 + ENFORCED = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + enforcement_mode = proto.Field( + proto.ENUM, + number=2, + enum=EnforcementMode, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for the + [GetService][google.firebase.appcheck.v1beta.ConfigService.GetService] + method. + + Attributes: + name (str): + Required. The relative resource name of the + [Service][google.firebase.appcheck.v1beta.Service] to + retrieve, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase Realtime + Database) + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + Attributes: + parent (str): + Required. The relative resource name of the parent project + for which to list each associated + [Service][google.firebase.appcheck.v1beta.Service], in the + format: + + :: + + projects/{project_number} + page_size (int): + The maximum number of + [Service][google.firebase.appcheck.v1beta.Service]s to + return in the response. Only explicitly configured services + are returned. + + The server may return fewer than this at its own discretion. + If no value is specified (or too large a value is + specified), the server will impose its own limit. + page_token (str): + Token returned from a previous call to + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + indicating where in the set of + [Service][google.firebase.appcheck.v1beta.Service]s to + resume listing. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + must match the call that provided the page token; if they do + not match, the result is undefined. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServicesResponse(proto.Message): + r"""Response message for the + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + method. + + Attributes: + services (Sequence[google.firebase.appcheck_v1beta.types.Service]): + The [Service][google.firebase.appcheck.v1beta.Service]s + retrieved. + next_page_token (str): + If the result list is too large to fit in a single response, + then a token is returned. If the string is empty or omitted, + then this response is the last page of results. + + This token can be used in a subsequent call to + [ListServices][google.firebase.appcheck.v1beta.ConfigService.ListServices] + to find the next group of + [Service][google.firebase.appcheck.v1beta.Service]s. + + Page tokens are short-lived and should not be persisted. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for the + [UpdateService][google.firebase.appcheck.v1beta.ConfigService.UpdateService] + method as well as an individual update message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + Attributes: + service (google.firebase.appcheck_v1beta.types.Service): + Required. The + [Service][google.firebase.appcheck.v1beta.Service] to + update. + + The [Service][google.firebase.appcheck.v1beta.Service]'s + ``name`` field is used to identify the + [Service][google.firebase.appcheck.v1beta.Service] to be + updated, in the format: + + :: + + projects/{project_number}/services/{service_id} + + Note that the ``service_id`` element must be a supported + service ID. Currently, the following service IDs are + supported: + + - ``firebasestorage.googleapis.com`` (Cloud Storage for + Firebase) + - ``firebasedatabase.googleapis.com`` (Firebase Realtime + Database) + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of names of fields in the + [Service][google.firebase.appcheck.v1beta.Service] to + update. Example: ``enforcement_mode``. + """ + + service = proto.Field( + proto.MESSAGE, + number=1, + message='Service', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateServicesRequest(proto.Message): + r"""Request message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + Attributes: + parent (str): + Required. The parent project name shared by all + [Service][google.firebase.appcheck.v1beta.Service] + configurations being updated, in the format + + :: + + projects/{project_number} + + The parent collection in the ``name`` field of any resource + being updated must match this field, or the entire batch + fails. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A comma-separated list of names of fields in the + [Service][google.firebase.appcheck.v1beta.Service]s to + update. Example: ``display_name``. + + If this field is present, the ``update_mask`` field in the + [UpdateServiceRequest][google.firebase.appcheck.v1beta.UpdateServiceRequest] + messages must all match this field, or the entire batch + fails and no updates will be committed. + requests (Sequence[google.firebase.appcheck_v1beta.types.UpdateServiceRequest]): + Required. The request messages specifying the + [Service][google.firebase.appcheck.v1beta.Service]s to + update. + + A maximum of 100 objects can be updated in a batch. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + requests = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='UpdateServiceRequest', + ) + + +class BatchUpdateServicesResponse(proto.Message): + r"""Response message for the + [BatchUpdateServices][google.firebase.appcheck.v1beta.ConfigService.BatchUpdateServices] + method. + + Attributes: + services (Sequence[google.firebase.appcheck_v1beta.types.Service]): + [Service][google.firebase.appcheck.v1beta.Service] objects + after the updates have been applied. + """ + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Service', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/firebase/appcheck_v1beta/types/token_exchange_service.py b/google/firebase/appcheck_v1beta/types/token_exchange_service.py new file mode 100644 index 000000000..588ef501d --- /dev/null +++ b/google/firebase/appcheck_v1beta/types/token_exchange_service.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.firebase.appcheck.v1beta', + manifest={ + 'GetPublicJwkSetRequest', + 'PublicJwkSet', + 'PublicJwk', + 'ExchangeSafetyNetTokenRequest', + 'ExchangeDeviceCheckTokenRequest', + 'ExchangeRecaptchaTokenRequest', + 'ExchangeCustomTokenRequest', + 'AttestationTokenResponse', + 'ExchangeDebugTokenRequest', + 'GenerateAppAttestChallengeRequest', + 'AppAttestChallengeResponse', + 'ExchangeAppAttestAttestationRequest', + 'ExchangeAppAttestAttestationResponse', + 'ExchangeAppAttestAssertionRequest', + }, +) + + +class GetPublicJwkSetRequest(proto.Message): + r"""Request message for the [GetPublicJwkSet][] method. + Attributes: + name (str): + Required. The relative resource name to the public JWK set. + Must always be exactly the string ``jwks``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class PublicJwkSet(proto.Message): + r"""The currently active set of public keys that can be used to verify + App Check tokens. + + This object is a JWK set as specified by `section 5 of RFC + 7517 `__. + + For security, the response **must not** be cached for longer than + one day. + + Attributes: + keys (Sequence[google.firebase.appcheck_v1beta.types.PublicJwk]): + The set of public keys. See `section 5.1 of RFC + 7517 `__. + """ + + keys = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PublicJwk', + ) + + +class PublicJwk(proto.Message): + r"""A JWK as specified by `section 4 of RFC + 7517 `__ and `section + 6.3.1 of RFC + 7518 `__. + + Attributes: + kty (str): + See `section 4.1 of RFC + 7517 `__. + use (str): + See `section 4.2 of RFC + 7517 `__. + alg (str): + See `section 4.4 of RFC + 7517 `__. + kid (str): + See `section 4.5 of RFC + 7517 `__. + n (str): + See `section 6.3.1.1 of RFC + 7518 `__. + e (str): + See `section 6.3.1.2 of RFC + 7518 `__. + """ + + kty = proto.Field( + proto.STRING, + number=1, + ) + use = proto.Field( + proto.STRING, + number=2, + ) + alg = proto.Field( + proto.STRING, + number=3, + ) + kid = proto.Field( + proto.STRING, + number=4, + ) + n = proto.Field( + proto.STRING, + number=5, + ) + e = proto.Field( + proto.STRING, + number=6, + ) + + +class ExchangeSafetyNetTokenRequest(proto.Message): + r"""Request message for the [ExchangeSafetyNetToken][] method. + Attributes: + app (str): + Required. The relative resource name of the Android app, in + the format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + safety_net_token (str): + The `SafetyNet attestation + response `__ + issued to your app. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + safety_net_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ExchangeDeviceCheckTokenRequest(proto.Message): + r"""Request message for the [ExchangeDeviceCheckToken][] method. + Attributes: + app (str): + Required. The relative resource name of the iOS app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + device_token (str): + The ``device_token`` as returned by Apple's client-side + `DeviceCheck + API `__. + This is the Base64 encoded ``Data`` (Swift) or ``NSData`` + (ObjC) object. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + device_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ExchangeRecaptchaTokenRequest(proto.Message): + r"""Request message for the [ExchangeRecaptchaToken][] method. + Attributes: + app (str): + Required. The relative resource name of the web app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + recaptcha_token (str): + The reCAPTCHA token as returned by the `reCAPTCHA v3 + JavaScript + API `__. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + recaptcha_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ExchangeCustomTokenRequest(proto.Message): + r"""Request message for the [ExchangeCustomToken][] method. + Attributes: + app (str): + Required. The relative resource name of the app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + custom_token (str): + A custom token signed using your project's + Admin SDK service account credentials. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + custom_token = proto.Field( + proto.STRING, + number=2, + ) + + +class AttestationTokenResponse(proto.Message): + r"""Encapsulates an *App Check token*, which are used to access Firebase + services protected by App Check. + + Attributes: + attestation_token (str): + An App Check token. + + App Check tokens are signed + `JWTs `__ containing + claims that identify the attested app and Firebase project. + This token is used to access Firebase services protected by + App Check. + ttl (google.protobuf.duration_pb2.Duration): + The duration from the time this token is + minted until its expiration. This field is + intended to ease client-side token management, + since the client may have clock skew, but is + still able to accurately measure a duration. + """ + + attestation_token = proto.Field( + proto.STRING, + number=1, + ) + ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ExchangeDebugTokenRequest(proto.Message): + r"""Request message for the [ExchangeDebugToken][] method. + Attributes: + app (str): + Required. The relative resource name of the app, in the + format: + + :: + + projects/{project_number}/apps/{app_id} + + If necessary, the ``project_number`` element can be replaced + with the project ID of the Firebase project. Learn more + about using project identifiers in Google's `AIP + 2510 `__ standard. + debug_token (str): + A debug token secret. This string must match a debug token + secret previously created using + [CreateDebugToken][google.firebase.appcheck.v1beta.ConfigService.CreateDebugToken]. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + debug_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GenerateAppAttestChallengeRequest(proto.Message): + r"""Request message for GenerateAppAttestChallenge + Attributes: + app (str): + Required. The full resource name to the iOS App. Format: + "projects/{project_id}/apps/{app_id}". + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + + +class AppAttestChallengeResponse(proto.Message): + r"""Response object for GenerateAppAttestChallenge + Attributes: + challenge (bytes): + A one time use challenge for the client to + pass to Apple's App Attest API. + ttl (google.protobuf.duration_pb2.Duration): + The duration from the time this challenge is + minted until it is expired. This field is + intended to ease client-side token management, + since the device may have clock skew, but is + still able to accurately measure a duration. + This expiration is intended to minimize the + replay window within which a single challenge + may be reused. + See AIP 142 for naming of this field. + """ + + challenge = proto.Field( + proto.BYTES, + number=1, + ) + ttl = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ExchangeAppAttestAttestationRequest(proto.Message): + r"""Request message for ExchangeAppAttestAttestation + Attributes: + app (str): + Required. The full resource name to the iOS App. Format: + "projects/{project_id}/apps/{app_id}". + attestation_statement (bytes): + The App Attest statement as returned by + Apple's client-side App Attest API. This is the + CBOR object returned by Apple, which will be + Base64 encoded in the JSON API. + challenge (bytes): + The challenge previously generated by the FAC + backend. + key_id (bytes): + The key ID generated by App Attest for the + client app. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + attestation_statement = proto.Field( + proto.BYTES, + number=2, + ) + challenge = proto.Field( + proto.BYTES, + number=3, + ) + key_id = proto.Field( + proto.BYTES, + number=4, + ) + + +class ExchangeAppAttestAttestationResponse(proto.Message): + r"""Response message for ExchangeAppAttestAttestation and + ExchangeAppAttestDebugAttestation + + Attributes: + artifact (bytes): + An artifact that should be passed back during + the Assertion flow. + attestation_token (google.firebase.appcheck_v1beta.types.AttestationTokenResponse): + An attestation token which can be used to + access Firebase APIs. + """ + + artifact = proto.Field( + proto.BYTES, + number=1, + ) + attestation_token = proto.Field( + proto.MESSAGE, + number=2, + message='AttestationTokenResponse', + ) + + +class ExchangeAppAttestAssertionRequest(proto.Message): + r"""Request message for ExchangeAppAttestAssertion + Attributes: + app (str): + Required. The full resource name to the iOS App. Format: + "projects/{project_id}/apps/{app_id}". + artifact (bytes): + The artifact previously returned by + ExchangeAppAttestAttestation. + assertion (bytes): + The CBOR encoded assertion provided by the + Apple App Attest SDK. + challenge (bytes): + A one time challenge returned by + GenerateAppAttestChallenge. + """ + + app = proto.Field( + proto.STRING, + number=1, + ) + artifact = proto.Field( + proto.BYTES, + number=2, + ) + assertion = proto.Field( + proto.BYTES, + number=3, + ) + challenge = proto.Field( + proto.BYTES, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest))