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))