diff --git a/.coveragerc b/.coveragerc index dd39c85..ba0f2ca 100644 --- a/.coveragerc +++ b/.coveragerc @@ -21,15 +21,14 @@ branch = True [report] fail_under = 100 show_missing = True +omit = google/cloud/secretmanager/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore abstract methods - raise NotImplementedError -omit = - */gapic/*.py - */proto/*.py - */core/*.py - */site-packages/*.py \ No newline at end of file + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound \ No newline at end of file diff --git a/README.rst b/README.rst index a5c268b..8849fd7 100644 --- a/README.rst +++ b/README.rst @@ -48,6 +48,17 @@ dependencies. .. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Python >= 3.6 + +Deprecated Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python == 2.7. + +The last version of this library compatible with Python 2.7 is google-cloud-secret-manager==1.0.0. + + Mac/Linux ^^^^^^^^^ diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..e810d13 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,164 @@ +# 2.0.0 Migration Guide + +The 2.0 release of the `google-cloud-secret-manager` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-secret-manager/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 2.0.0 release requires Python 3.6+. + + +## Method Calls + +> **WARNING**: Breaking change + +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-secret-manager +``` + +* The script `fixup_secretmanager_v1_keywords.py` is shipped with the library. It expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_secretmanager_v1_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import secretmanager_v1 + +client = secretmanager_v1.SecretManagerServiceClient() + +secret = client.get_secret("secret_name") +``` + + +**After:** +```py +from google.cloud import secretmanager_v1 + +client = secretmanager_v1.SecretManagerServiceClient() + +secret = client.get_secret(request={'name': "secret_name"}) +``` + +### More Details + +In `google-cloud-secret-manager<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def create_secret( + self, + parent, + secret_id, + secret, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the `google.api.method_signature` annotation specified by the API producer. + + +**After:** +```py + def create_secret( + self, + request: service.CreateSecretRequest = None, + *, + parent: str = None, + secret_id: str = None, + secret: resources.Secret = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.create_secret( + request={ + "parent": parent, + "secret_id": secret_id, + "secret": secret + } +) +``` + +```py +response = client.create_secret( + parent=parent, + secret_id=secret_id, + secret=secret +) +``` + +This call is invalid because it mixes `request` with a keyword argument `secret`. Executing this code +will result in an error. + +```py +response = client.create_secret( + request={ + "parent": parent, + "secret_id": secret_id + }, + secret=secret +) +``` + + + +## Enums and Types + + +> **WARNING**: Breaking change + +The submodules `enums` and `types` have been removed. + +**Before:** +```py +from google.cloud import secretmanager_v1 + +secret_version = secretmanager_v1.enums.SecretVersion.ENABLED +secret = secretmanager_v1.types.Secret(name="name") +``` + + +**After:** +```py +from google.cloud import secretmanager_v1 + +secret_version = secretmanager_v1.SecretVersion.ENABLED +secret = secretmanager_v1.Secret(name="name") +``` + +## Path Helper Methods + +The following path helper methods have been removed. Please construct +the paths manually. + +```py +project = 'my-project' +secret = 'secret' +secret_version = 'secret_version' + +project_path = f'projects/{project}' +secret_version_path = f'projects/{project}/secrets/{secret}/versions/{secret_version}' +``` \ No newline at end of file diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md new file mode 120000 index 0000000..01097c8 --- /dev/null +++ b/docs/UPGRADING.md @@ -0,0 +1 @@ +../UPGRADING.md \ No newline at end of file diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 126fdad..0000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Secret Manager API -============================= - -.. automodule:: google.cloud.secretmanager_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 28b0dc4..0000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Secret Manager API Client -=================================== - -.. automodule:: google.cloud.secretmanager_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst deleted file mode 100644 index 4b5cb5e..0000000 --- a/docs/gapic/v1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Secret Manager API -============================= - -.. automodule:: google.cloud.secretmanager_v1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst deleted file mode 100644 index 823a04d..0000000 --- a/docs/gapic/v1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Secret Manager API Client -=================================== - -.. automodule:: google.cloud.secretmanager_v1beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 0d244ab..ffaff42 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,16 +7,26 @@ v1 Api Reference .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + secretmanager_v1/services + secretmanager_v1/types v1beta1 Api Reference --------------------- .. toctree:: :maxdepth: 2 - gapic/v1beta1/api - gapic/v1beta1/types + secretmanager_v1beta1/services + secretmanager_v1beta1/types + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING Changelog --------- diff --git a/docs/secretmanager_v1/services.rst b/docs/secretmanager_v1/services.rst new file mode 100644 index 0000000..2454edf --- /dev/null +++ b/docs/secretmanager_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Secretmanager v1 API +============================================== + +.. automodule:: google.cloud.secretmanager_v1.services.secret_manager_service + :members: + :inherited-members: diff --git a/docs/secretmanager_v1/types.rst b/docs/secretmanager_v1/types.rst new file mode 100644 index 0000000..cda1657 --- /dev/null +++ b/docs/secretmanager_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Secretmanager v1 API +=========================================== + +.. automodule:: google.cloud.secretmanager_v1.types + :members: diff --git a/docs/secretmanager_v1beta1/services.rst b/docs/secretmanager_v1beta1/services.rst new file mode 100644 index 0000000..e548f90 --- /dev/null +++ b/docs/secretmanager_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Secretmanager v1beta1 API +=================================================== + +.. automodule:: google.cloud.secretmanager_v1beta1.services.secret_manager_service + :members: + :inherited-members: diff --git a/docs/secretmanager_v1beta1/types.rst b/docs/secretmanager_v1beta1/types.rst new file mode 100644 index 0000000..a1dcc16 --- /dev/null +++ b/docs/secretmanager_v1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Secretmanager v1beta1 API +================================================ + +.. automodule:: google.cloud.secretmanager_v1beta1.types + :members: diff --git a/google/cloud/secretmanager/__init__.py b/google/cloud/secretmanager/__init__.py new file mode 100644 index 0000000..367a974 --- /dev/null +++ b/google/cloud/secretmanager/__init__.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.secretmanager_v1.services.secret_manager_service.async_client import ( + SecretManagerServiceAsyncClient, +) +from google.cloud.secretmanager_v1.services.secret_manager_service.client import ( + SecretManagerServiceClient, +) +from google.cloud.secretmanager_v1.types.resources import CustomerManagedEncryption +from google.cloud.secretmanager_v1.types.resources import ( + CustomerManagedEncryptionStatus, +) +from google.cloud.secretmanager_v1.types.resources import Replication +from google.cloud.secretmanager_v1.types.resources import ReplicationStatus +from google.cloud.secretmanager_v1.types.resources import Secret +from google.cloud.secretmanager_v1.types.resources import SecretPayload +from google.cloud.secretmanager_v1.types.resources import SecretVersion +from google.cloud.secretmanager_v1.types.service import AccessSecretVersionRequest +from google.cloud.secretmanager_v1.types.service import AccessSecretVersionResponse +from google.cloud.secretmanager_v1.types.service import AddSecretVersionRequest +from google.cloud.secretmanager_v1.types.service import CreateSecretRequest +from google.cloud.secretmanager_v1.types.service import DeleteSecretRequest +from google.cloud.secretmanager_v1.types.service import DestroySecretVersionRequest +from google.cloud.secretmanager_v1.types.service import DisableSecretVersionRequest +from google.cloud.secretmanager_v1.types.service import EnableSecretVersionRequest +from google.cloud.secretmanager_v1.types.service import GetSecretRequest +from google.cloud.secretmanager_v1.types.service import GetSecretVersionRequest +from google.cloud.secretmanager_v1.types.service import ListSecretVersionsRequest +from google.cloud.secretmanager_v1.types.service import ListSecretVersionsResponse +from google.cloud.secretmanager_v1.types.service import ListSecretsRequest +from google.cloud.secretmanager_v1.types.service import ListSecretsResponse +from google.cloud.secretmanager_v1.types.service import UpdateSecretRequest + +__all__ = ( + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "AddSecretVersionRequest", + "CreateSecretRequest", + "CustomerManagedEncryption", + "CustomerManagedEncryptionStatus", + "DeleteSecretRequest", + "DestroySecretVersionRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "GetSecretRequest", + "GetSecretVersionRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "ListSecretsRequest", + "ListSecretsResponse", + "Replication", + "ReplicationStatus", + "Secret", + "SecretManagerServiceAsyncClient", + "SecretManagerServiceClient", + "SecretPayload", + "SecretVersion", + "UpdateSecretRequest", +) diff --git a/google/cloud/secretmanager/py.typed b/google/cloud/secretmanager/py.typed new file mode 100644 index 0000000..188cc03 --- /dev/null +++ b/google/cloud/secretmanager/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-secretmanager package uses inline types. diff --git a/google/cloud/secretmanager_v1/__init__.py b/google/cloud/secretmanager_v1/__init__.py index c2d69d7..f0bc5f9 100644 --- a/google/cloud/secretmanager_v1/__init__.py +++ b/google/cloud/secretmanager_v1/__init__.py @@ -1,47 +1,67 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.secretmanager_v1 import types -from google.cloud.secretmanager_v1.gapic import enums -from google.cloud.secretmanager_v1.gapic import secret_manager_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecretManagerServiceClient( - secret_manager_service_client.SecretManagerServiceClient -): - __doc__ = secret_manager_service_client.SecretManagerServiceClient.__doc__ - enums = enums +from .services.secret_manager_service import SecretManagerServiceClient +from .types.resources import CustomerManagedEncryption +from .types.resources import CustomerManagedEncryptionStatus +from .types.resources import Replication +from .types.resources import ReplicationStatus +from .types.resources import Secret +from .types.resources import SecretPayload +from .types.resources import SecretVersion +from .types.service import AccessSecretVersionRequest +from .types.service import AccessSecretVersionResponse +from .types.service import AddSecretVersionRequest +from .types.service import CreateSecretRequest +from .types.service import DeleteSecretRequest +from .types.service import DestroySecretVersionRequest +from .types.service import DisableSecretVersionRequest +from .types.service import EnableSecretVersionRequest +from .types.service import GetSecretRequest +from .types.service import GetSecretVersionRequest +from .types.service import ListSecretVersionsRequest +from .types.service import ListSecretVersionsResponse +from .types.service import ListSecretsRequest +from .types.service import ListSecretsResponse +from .types.service import UpdateSecretRequest __all__ = ( - "enums", - "types", + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "AddSecretVersionRequest", + "CreateSecretRequest", + "CustomerManagedEncryption", + "CustomerManagedEncryptionStatus", + "DeleteSecretRequest", + "DestroySecretVersionRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "GetSecretRequest", + "GetSecretVersionRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "ListSecretsRequest", + "ListSecretsResponse", + "Replication", + "ReplicationStatus", + "Secret", + "SecretPayload", + "SecretVersion", + "UpdateSecretRequest", "SecretManagerServiceClient", ) diff --git a/google/cloud/secretmanager_v1/gapic/__init__.py b/google/cloud/secretmanager_v1/gapic/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/secretmanager_v1/gapic/enums.py b/google/cloud/secretmanager_v1/gapic/enums.py deleted file mode 100644 index e77df68..0000000 --- a/google/cloud/secretmanager_v1/gapic/enums.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class SecretVersion(object): - class State(enum.IntEnum): - """ - The state of a ``SecretVersion``, indicating if it can be accessed. - - Attributes: - STATE_UNSPECIFIED (int): Not specified. This value is unused and invalid. - ENABLED (int): The ``SecretVersion`` may be accessed. - DISABLED (int): The ``SecretVersion`` may not be accessed, but the secret data is - still available and can be placed back into the ``ENABLED`` state. - DESTROYED (int): The ``SecretVersion`` is destroyed and the secret data is no longer - stored. A version may not leave this state once entered. - """ - - STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - DESTROYED = 3 diff --git a/google/cloud/secretmanager_v1/gapic/secret_manager_service_client.py b/google/cloud/secretmanager_v1/gapic/secret_manager_service_client.py deleted file mode 100644 index fcd3d12..0000000 --- a/google/cloud/secretmanager_v1/gapic/secret_manager_service_client.py +++ /dev/null @@ -1,1439 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.secretmanager.v1 SecretManagerService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.secretmanager_v1.gapic import enums -from google.cloud.secretmanager_v1.gapic import secret_manager_service_client_config -from google.cloud.secretmanager_v1.gapic.transports import ( - secret_manager_service_grpc_transport, -) -from google.cloud.secretmanager_v1.proto import resources_pb2 -from google.cloud.secretmanager_v1.proto import service_pb2 -from google.cloud.secretmanager_v1.proto import service_pb2_grpc -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-secret-manager", -).version - - -class SecretManagerServiceClient(object): - """ - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - - ``Secret`` - - ``SecretVersion`` - """ - - SERVICE_ADDRESS = "secretmanager.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.secretmanager.v1.SecretManagerService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SecretManagerServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def project_path(cls, project): - """Return a fully-qualified project string.""" - return google.api_core.path_template.expand( - "projects/{project}", project=project, - ) - - @classmethod - def secret_path(cls, project, secret): - """Return a fully-qualified secret string.""" - return google.api_core.path_template.expand( - "projects/{project}/secrets/{secret}", project=project, secret=secret, - ) - - @classmethod - def secret_version_path(cls, project, secret, secret_version): - """Return a fully-qualified secret_version string.""" - return google.api_core.path_template.expand( - "projects/{project}/secrets/{secret}/versions/{secret_version}", - project=project, - secret=secret, - secret_version=secret_version, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.SecretManagerServiceGrpcTransport, - Callable[[~.Credentials, type], ~.SecretManagerServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = secret_manager_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=secret_manager_service_grpc_transport.SecretManagerServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = secret_manager_service_grpc_transport.SecretManagerServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_secrets( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ``Secrets``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> parent = client.project_path('[PROJECT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_secrets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_secrets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The resource name of the project associated with the - ``Secrets``, in the format ``projects/*``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.secretmanager_v1.types.Secret` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_secrets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_secrets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_secrets, - default_retry=self._method_configs["ListSecrets"].retry, - default_timeout=self._method_configs["ListSecrets"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListSecretsRequest(parent=parent, page_size=page_size,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_secrets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="secrets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def create_secret( - self, - parent, - secret_id, - secret, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a new ``Secret`` containing no ``SecretVersions``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> parent = client.project_path('[PROJECT]') - >>> - >>> # TODO: Initialize `secret_id`: - >>> secret_id = '' - >>> - >>> # TODO: Initialize `secret`: - >>> secret = {} - >>> - >>> response = client.create_secret(parent, secret_id, secret) - - Args: - parent (str): Required. The resource name of the project to associate with the - ``Secret``, in the format ``projects/*``. - secret_id (str): Required. This must be unique within the project. - - A secret ID is a string with a maximum length of 255 characters and can - contain uppercase and lowercase letters, numerals, and the hyphen - (``-``) and underscore (``_``) characters. - secret (Union[dict, ~google.cloud.secretmanager_v1.types.Secret]): Required. A ``Secret`` with initial field values. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1.types.Secret` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.Secret` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "create_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_secret, - default_retry=self._method_configs["CreateSecret"].retry, - default_timeout=self._method_configs["CreateSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.CreateSecretRequest( - parent=parent, secret_id=secret_id, secret=secret, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def add_secret_version( - self, - parent, - payload, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a new ``SecretVersion`` containing secret data and attaches - it to an existing ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> parent = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> # TODO: Initialize `payload`: - >>> payload = {} - >>> - >>> response = client.add_secret_version(parent, payload) - - Args: - parent (str): Required. The resource name of the ``Secret`` to associate with the - ``SecretVersion`` in the format ``projects/*/secrets/*``. - payload (Union[dict, ~google.cloud.secretmanager_v1.types.SecretPayload]): Required. The secret payload of the ``SecretVersion``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1.types.SecretPayload` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "add_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "add_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.add_secret_version, - default_retry=self._method_configs["AddSecretVersion"].retry, - default_timeout=self._method_configs["AddSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.AddSecretVersionRequest(parent=parent, payload=payload,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["add_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_secret( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets metadata for a given ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> response = client.get_secret(name) - - Args: - name (str): Required. The resource name of the ``Secret``, in the format - ``projects/*/secrets/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.Secret` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "get_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_secret, - default_retry=self._method_configs["GetSecret"].retry, - default_timeout=self._method_configs["GetSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetSecretRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_secret( - self, - secret, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates metadata of an existing ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `secret`: - >>> secret = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_secret(secret, update_mask) - - Args: - secret (Union[dict, ~google.cloud.secretmanager_v1.types.Secret]): Required. ``Secret`` with updated field values. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1.types.Secret` - update_mask (Union[dict, ~google.cloud.secretmanager_v1.types.FieldMask]): Required. Specifies the fields to be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.Secret` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "update_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_secret, - default_retry=self._method_configs["UpdateSecret"].retry, - default_timeout=self._method_configs["UpdateSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.UpdateSecretRequest( - secret=secret, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("secret.name", secret.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_secret( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> client.delete_secret(name) - - Args: - name (str): Required. The resource name of the ``Secret`` to delete in the - format ``projects/*/secrets/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_secret, - default_retry=self._method_configs["DeleteSecret"].retry, - default_timeout=self._method_configs["DeleteSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DeleteSecretRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_secret_versions( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ``SecretVersions``. This call does not return secret data. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> parent = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> # Iterate over all results - >>> for element in client.list_secret_versions(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_secret_versions(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The resource name of the ``Secret`` associated with the - ``SecretVersions`` to list, in the format ``projects/*/secrets/*``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.secretmanager_v1.types.SecretVersion` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_secret_versions" not in self._inner_api_calls: - self._inner_api_calls[ - "list_secret_versions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_secret_versions, - default_retry=self._method_configs["ListSecretVersions"].retry, - default_timeout=self._method_configs["ListSecretVersions"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListSecretVersionsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_secret_versions"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="versions", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets metadata for a ``SecretVersion``. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.get_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` in the format - ``projects/*/secrets/*/versions/*``. - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "get_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_secret_version, - default_retry=self._method_configs["GetSecretVersion"].retry, - default_timeout=self._method_configs["GetSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def access_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Accesses a ``SecretVersion``. This call returns the secret data. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.access_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` in the format - ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.AccessSecretVersionResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "access_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "access_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.access_secret_version, - default_retry=self._method_configs["AccessSecretVersion"].retry, - default_timeout=self._method_configs["AccessSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.AccessSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["access_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def disable_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Disables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DISABLED``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.disable_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` to disable in - the format ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "disable_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "disable_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.disable_secret_version, - default_retry=self._method_configs["DisableSecretVersion"].retry, - default_timeout=self._method_configs["DisableSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DisableSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["disable_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def enable_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Enables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``ENABLED``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.enable_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` to enable in - the format ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "enable_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "enable_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.enable_secret_version, - default_retry=self._method_configs["EnableSecretVersion"].retry, - default_timeout=self._method_configs["EnableSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.EnableSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["enable_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def destroy_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Destroys a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DESTROYED`` and - irrevocably destroys the secret data. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.destroy_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` to destroy in - the format ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "destroy_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "destroy_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.destroy_secret_version, - default_retry=self._method_configs["DestroySecretVersion"].retry, - default_timeout=self._method_configs["DestroySecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DestroySecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["destroy_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def set_iam_policy( - self, - resource, - policy, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sets the access control policy on the specified secret. Replaces any - existing policy. - - Permissions on ``SecretVersions`` are enforced according to the policy - set on the associated ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `policy`: - >>> policy = {} - >>> - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (str): REQUIRED: The resource for which the policy is being specified. - See the operation documentation for the appropriate value for this field. - policy (Union[dict, ~google.cloud.secretmanager_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The - size of the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1.types.Policy` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "set_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_iam_policy, - default_retry=self._method_configs["SetIamPolicy"].retry, - default_timeout=self._method_configs["SetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_iam_policy( - self, - resource, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the access control policy for a secret. - Returns empty policy if the secret exists and does not have a policy set. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> response = client.get_iam_policy(resource) - - Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.secretmanager_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1.types.GetPolicyOptions` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "get_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns permissions that a caller has for the specified secret. If - the secret does not exist, this call returns an empty set of - permissions, not a NOT_FOUND error. - - Note: This operation is designed to be used for building - permission-aware UIs and command-line tools, not for authorization - checking. This operation may "fail open" without warning. - - Example: - >>> from google.cloud import secretmanager_v1 - >>> - >>> client = secretmanager_v1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[str]): The set of permissions to check for the ``resource``. Permissions - with wildcards (such as '*' or 'storage.*') are not allowed. For more - information see `IAM - Overview `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/secretmanager_v1/gapic/secret_manager_service_client_config.py b/google/cloud/secretmanager_v1/gapic/secret_manager_service_client_config.py deleted file mode 100644 index 513bbef..0000000 --- a/google/cloud/secretmanager_v1/gapic/secret_manager_service_client_config.py +++ /dev/null @@ -1,117 +0,0 @@ -config = { - "interfaces": { - "google.cloud.secretmanager.v1.SecretManagerService": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "UNKNOWN"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 1000, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ListSecrets": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "AddSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DeleteSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "ListSecretVersions": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "AccessSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "DisableSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "EnableSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DestroySecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - }, - } - } -} diff --git a/google/cloud/secretmanager_v1/gapic/transports/__init__.py b/google/cloud/secretmanager_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/secretmanager_v1/gapic/transports/secret_manager_service_grpc_transport.py b/google/cloud/secretmanager_v1/gapic/transports/secret_manager_service_grpc_transport.py deleted file mode 100644 index edb4642..0000000 --- a/google/cloud/secretmanager_v1/gapic/transports/secret_manager_service_grpc_transport.py +++ /dev/null @@ -1,330 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.secretmanager_v1.proto import service_pb2_grpc - - -class SecretManagerServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.secretmanager.v1 SecretManagerService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="secretmanager.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "secret_manager_service_stub": service_pb2_grpc.SecretManagerServiceStub( - channel - ), - } - - @classmethod - def create_channel( - cls, address="secretmanager.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_secrets(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.list_secrets`. - - Lists ``Secrets``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].ListSecrets - - @property - def create_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.create_secret`. - - Creates a new ``Secret`` containing no ``SecretVersions``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].CreateSecret - - @property - def add_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.add_secret_version`. - - Creates a new ``SecretVersion`` containing secret data and attaches - it to an existing ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].AddSecretVersion - - @property - def get_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.get_secret`. - - Gets metadata for a given ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].GetSecret - - @property - def update_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.update_secret`. - - Updates metadata of an existing ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].UpdateSecret - - @property - def delete_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.delete_secret`. - - Deletes a ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].DeleteSecret - - @property - def list_secret_versions(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.list_secret_versions`. - - Lists ``SecretVersions``. This call does not return secret data. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].ListSecretVersions - - @property - def get_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.get_secret_version`. - - Gets metadata for a ``SecretVersion``. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].GetSecretVersion - - @property - def access_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.access_secret_version`. - - Accesses a ``SecretVersion``. This call returns the secret data. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].AccessSecretVersion - - @property - def disable_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.disable_secret_version`. - - Disables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DISABLED``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].DisableSecretVersion - - @property - def enable_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.enable_secret_version`. - - Enables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``ENABLED``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].EnableSecretVersion - - @property - def destroy_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.destroy_secret_version`. - - Destroys a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DESTROYED`` and - irrevocably destroys the secret data. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].DestroySecretVersion - - @property - def set_iam_policy(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.set_iam_policy`. - - Sets the access control policy on the specified secret. Replaces any - existing policy. - - Permissions on ``SecretVersions`` are enforced according to the policy - set on the associated ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].SetIamPolicy - - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.get_iam_policy`. - - Gets the access control policy for a secret. - Returns empty policy if the secret exists and does not have a policy set. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].GetIamPolicy - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.test_iam_permissions`. - - Returns permissions that a caller has for the specified secret. If - the secret does not exist, this call returns an empty set of - permissions, not a NOT_FOUND error. - - Note: This operation is designed to be used for building - permission-aware UIs and command-line tools, not for authorization - checking. This operation may "fail open" without warning. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].TestIamPermissions diff --git a/google/cloud/secretmanager_v1/proto/__init__.py b/google/cloud/secretmanager_v1/proto/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/secretmanager_v1/proto/resources_pb2.py b/google/cloud/secretmanager_v1/proto/resources_pb2.py deleted file mode 100644 index 4664373..0000000 --- a/google/cloud/secretmanager_v1/proto/resources_pb2.py +++ /dev/null @@ -1,800 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/secretmanager_v1/proto/resources.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/secretmanager_v1/proto/resources.proto", - package="google.cloud.secretmanager.v1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.secretmanager.v1B\016ResourcesProtoP\001ZJgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1;secretmanager\370\001\001\242\002\003GSM\252\002\035Google.Cloud.SecretManager.V1\312\002\035Google\\Cloud\\SecretManager\\V1\352\002 Google::Cloud::SecretManager::V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n3google/cloud/secretmanager_v1/proto/resources.proto\x12\x1dgoogle.cloud.secretmanager.v1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto"\xdb\x02\n\x06Secret\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x03\x12G\n\x0breplication\x18\x02 \x01(\x0b\x32*.google.cloud.secretmanager.v1.ReplicationB\x06\xe0\x41\x05\xe0\x41\x02\x12\x34\n\x0b\x63reate_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x41\n\x06labels\x18\x04 \x03(\x0b\x32\x31.google.cloud.secretmanager.v1.Secret.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01:M\xea\x41J\n#secretmanager.googleapis.com/Secret\x12#projects/{project}/secrets/{secret}"\x91\x03\n\rSecretVersion\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x03\x12\x34\n\x0b\x63reate_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x35\n\x0c\x64\x65stroy_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x46\n\x05state\x18\x04 \x01(\x0e\x32\x32.google.cloud.secretmanager.v1.SecretVersion.StateB\x03\xe0\x41\x03"H\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x45NABLED\x10\x01\x12\x0c\n\x08\x44ISABLED\x10\x02\x12\r\n\tDESTROYED\x10\x03:n\xea\x41k\n*secretmanager.googleapis.com/SecretVersion\x12=projects/{project}/secrets/{secret}/versions/{secret_version}"\xc8\x02\n\x0bReplication\x12I\n\tautomatic\x18\x01 \x01(\x0b\x32\x34.google.cloud.secretmanager.v1.Replication.AutomaticH\x00\x12N\n\x0cuser_managed\x18\x02 \x01(\x0b\x32\x36.google.cloud.secretmanager.v1.Replication.UserManagedH\x00\x1a\x0b\n\tAutomatic\x1a\x81\x01\n\x0bUserManaged\x12U\n\x08replicas\x18\x01 \x03(\x0b\x32>.google.cloud.secretmanager.v1.Replication.UserManaged.ReplicaB\x03\xe0\x41\x02\x1a\x1b\n\x07Replica\x12\x10\n\x08location\x18\x01 \x01(\tB\r\n\x0breplication"\x1d\n\rSecretPayload\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x42\xed\x01\n!com.google.cloud.secretmanager.v1B\x0eResourcesProtoP\x01ZJgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1;secretmanager\xf8\x01\x01\xa2\x02\x03GSM\xaa\x02\x1dGoogle.Cloud.SecretManager.V1\xca\x02\x1dGoogle\\Cloud\\SecretManager\\V1\xea\x02 Google::Cloud::SecretManager::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_SECRETVERSION_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.secretmanager.v1.SecretVersion.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ENABLED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DISABLED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DESTROYED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=777, - serialized_end=849, -) -_sym_db.RegisterEnumDescriptor(_SECRETVERSION_STATE) - - -_SECRET_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.secretmanager.v1.Secret.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.secretmanager.v1.Secret.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.secretmanager.v1.Secret.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=433, - serialized_end=478, -) - -_SECRET = _descriptor.Descriptor( - name="Secret", - full_name="google.cloud.secretmanager.v1.Secret", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.Secret.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="replication", - full_name="google.cloud.secretmanager.v1.Secret.replication", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\005\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.secretmanager.v1.Secret.create_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.secretmanager.v1.Secret.labels", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SECRET_LABELSENTRY,], - enum_types=[], - serialized_options=b"\352AJ\n#secretmanager.googleapis.com/Secret\022#projects/{project}/secrets/{secret}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=210, - serialized_end=557, -) - - -_SECRETVERSION = _descriptor.Descriptor( - name="SecretVersion", - full_name="google.cloud.secretmanager.v1.SecretVersion", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.SecretVersion.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.secretmanager.v1.SecretVersion.create_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="destroy_time", - full_name="google.cloud.secretmanager.v1.SecretVersion.destroy_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.secretmanager.v1.SecretVersion.state", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_SECRETVERSION_STATE,], - serialized_options=b"\352Ak\n*secretmanager.googleapis.com/SecretVersion\022=projects/{project}/secrets/{secret}/versions/{secret_version}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=560, - serialized_end=961, -) - - -_REPLICATION_AUTOMATIC = _descriptor.Descriptor( - name="Automatic", - full_name="google.cloud.secretmanager.v1.Replication.Automatic", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1134, - serialized_end=1145, -) - -_REPLICATION_USERMANAGED_REPLICA = _descriptor.Descriptor( - name="Replica", - full_name="google.cloud.secretmanager.v1.Replication.UserManaged.Replica", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="location", - full_name="google.cloud.secretmanager.v1.Replication.UserManaged.Replica.location", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1250, - serialized_end=1277, -) - -_REPLICATION_USERMANAGED = _descriptor.Descriptor( - name="UserManaged", - full_name="google.cloud.secretmanager.v1.Replication.UserManaged", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="replicas", - full_name="google.cloud.secretmanager.v1.Replication.UserManaged.replicas", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_REPLICATION_USERMANAGED_REPLICA,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1148, - serialized_end=1277, -) - -_REPLICATION = _descriptor.Descriptor( - name="Replication", - full_name="google.cloud.secretmanager.v1.Replication", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="automatic", - full_name="google.cloud.secretmanager.v1.Replication.automatic", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="user_managed", - full_name="google.cloud.secretmanager.v1.Replication.user_managed", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_REPLICATION_AUTOMATIC, _REPLICATION_USERMANAGED,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="replication", - full_name="google.cloud.secretmanager.v1.Replication.replication", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=964, - serialized_end=1292, -) - - -_SECRETPAYLOAD = _descriptor.Descriptor( - name="SecretPayload", - full_name="google.cloud.secretmanager.v1.SecretPayload", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.secretmanager.v1.SecretPayload.data", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1294, - serialized_end=1323, -) - -_SECRET_LABELSENTRY.containing_type = _SECRET -_SECRET.fields_by_name["replication"].message_type = _REPLICATION -_SECRET.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SECRET.fields_by_name["labels"].message_type = _SECRET_LABELSENTRY -_SECRETVERSION.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SECRETVERSION.fields_by_name[ - "destroy_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SECRETVERSION.fields_by_name["state"].enum_type = _SECRETVERSION_STATE -_SECRETVERSION_STATE.containing_type = _SECRETVERSION -_REPLICATION_AUTOMATIC.containing_type = _REPLICATION -_REPLICATION_USERMANAGED_REPLICA.containing_type = _REPLICATION_USERMANAGED -_REPLICATION_USERMANAGED.fields_by_name[ - "replicas" -].message_type = _REPLICATION_USERMANAGED_REPLICA -_REPLICATION_USERMANAGED.containing_type = _REPLICATION -_REPLICATION.fields_by_name["automatic"].message_type = _REPLICATION_AUTOMATIC -_REPLICATION.fields_by_name["user_managed"].message_type = _REPLICATION_USERMANAGED -_REPLICATION.oneofs_by_name["replication"].fields.append( - _REPLICATION.fields_by_name["automatic"] -) -_REPLICATION.fields_by_name["automatic"].containing_oneof = _REPLICATION.oneofs_by_name[ - "replication" -] -_REPLICATION.oneofs_by_name["replication"].fields.append( - _REPLICATION.fields_by_name["user_managed"] -) -_REPLICATION.fields_by_name[ - "user_managed" -].containing_oneof = _REPLICATION.oneofs_by_name["replication"] -DESCRIPTOR.message_types_by_name["Secret"] = _SECRET -DESCRIPTOR.message_types_by_name["SecretVersion"] = _SECRETVERSION -DESCRIPTOR.message_types_by_name["Replication"] = _REPLICATION -DESCRIPTOR.message_types_by_name["SecretPayload"] = _SECRETPAYLOAD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Secret = _reflection.GeneratedProtocolMessageType( - "Secret", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _SECRET_LABELSENTRY, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.Secret.LabelsEntry) - }, - ), - "DESCRIPTOR": _SECRET, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """A [Secret][google.cloud.secretmanager.v1.Secret] is a logical secret - whose value and versions can be accessed. A - [Secret][google.cloud.secretmanager.v1.Secret] is made up of zero or - more [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] - that represent the secret data. - - Attributes: - name: - Output only. The resource name of the - [Secret][google.cloud.secretmanager.v1.Secret] in the format - ``projects/*/secrets/*``. - replication: - Required. Immutable. The replication policy of the secret data - attached to the - [Secret][google.cloud.secretmanager.v1.Secret]. The - replication policy cannot be changed after the Secret has been - created. - create_time: - Output only. The time at which the - [Secret][google.cloud.secretmanager.v1.Secret] was created. - labels: - The labels assigned to this Secret. Label keys must be - between 1 and 63 characters long, have a UTF-8 encoding of - maximum 128 bytes, and must conform to the following PCRE - regular expression: - ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}`` Label values - must be between 0 and 63 characters long, have a UTF-8 - encoding of maximum 128 bytes, and must conform to the - following PCRE regular expression: - ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}`` No more than 64 labels can be - assigned to a given resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.Secret) - }, -) -_sym_db.RegisterMessage(Secret) -_sym_db.RegisterMessage(Secret.LabelsEntry) - -SecretVersion = _reflection.GeneratedProtocolMessageType( - "SecretVersion", - (_message.Message,), - { - "DESCRIPTOR": _SECRETVERSION, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """A secret version resource in the Secret Manager API. - - Attributes: - name: - Output only. The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - in the format ``projects/*/secrets/*/versions/*``. - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - IDs in a [Secret][google.cloud.secretmanager.v1.Secret] start - at 1 and are incremented for each subsequent version of the - secret. - create_time: - Output only. The time at which the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - was created. - destroy_time: - Output only. The time this - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - was destroyed. Only present if - [state][google.cloud.secretmanager.v1.SecretVersion.state] is - [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State. - DESTROYED]. - state: - Output only. The current state of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.SecretVersion) - }, -) -_sym_db.RegisterMessage(SecretVersion) - -Replication = _reflection.GeneratedProtocolMessageType( - "Replication", - (_message.Message,), - { - "Automatic": _reflection.GeneratedProtocolMessageType( - "Automatic", - (_message.Message,), - { - "DESCRIPTOR": _REPLICATION_AUTOMATIC, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """A replication policy that replicates the - [Secret][google.cloud.secretmanager.v1.Secret] payload without any - restrictions.""", - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.Replication.Automatic) - }, - ), - "UserManaged": _reflection.GeneratedProtocolMessageType( - "UserManaged", - (_message.Message,), - { - "Replica": _reflection.GeneratedProtocolMessageType( - "Replica", - (_message.Message,), - { - "DESCRIPTOR": _REPLICATION_USERMANAGED_REPLICA, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """Represents a Replica for this - [Secret][google.cloud.secretmanager.v1.Secret]. - - Attributes: - location: - The canonical IDs of the location to replicate data. For - example: ``"us-east1"``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.Replication.UserManaged.Replica) - }, - ), - "DESCRIPTOR": _REPLICATION_USERMANAGED, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """A replication policy that replicates the - [Secret][google.cloud.secretmanager.v1.Secret] payload into the - locations specified in [Secret.replication.user_managed.replicas][] - - Attributes: - replicas: - Required. The list of Replicas for this - [Secret][google.cloud.secretmanager.v1.Secret]. Cannot be - empty. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.Replication.UserManaged) - }, - ), - "DESCRIPTOR": _REPLICATION, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """A policy that defines the replication configuration of data. - - Attributes: - replication: - The replication policy for this secret. - automatic: - The [Secret][google.cloud.secretmanager.v1.Secret] will - automatically be replicated without any restrictions. - user_managed: - The [Secret][google.cloud.secretmanager.v1.Secret] will only - be replicated into the locations specified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.Replication) - }, -) -_sym_db.RegisterMessage(Replication) -_sym_db.RegisterMessage(Replication.Automatic) -_sym_db.RegisterMessage(Replication.UserManaged) -_sym_db.RegisterMessage(Replication.UserManaged.Replica) - -SecretPayload = _reflection.GeneratedProtocolMessageType( - "SecretPayload", - (_message.Message,), - { - "DESCRIPTOR": _SECRETPAYLOAD, - "__module__": "google.cloud.secretmanager_v1.proto.resources_pb2", - "__doc__": """A secret payload resource in the Secret Manager API. This contains the - sensitive secret payload that is associated with a - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Attributes: - data: - The secret data. Must be no larger than 64KiB. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.SecretPayload) - }, -) -_sym_db.RegisterMessage(SecretPayload) - - -DESCRIPTOR._options = None -_SECRET_LABELSENTRY._options = None -_SECRET.fields_by_name["name"]._options = None -_SECRET.fields_by_name["replication"]._options = None -_SECRET.fields_by_name["create_time"]._options = None -_SECRET._options = None -_SECRETVERSION.fields_by_name["name"]._options = None -_SECRETVERSION.fields_by_name["create_time"]._options = None -_SECRETVERSION.fields_by_name["destroy_time"]._options = None -_SECRETVERSION.fields_by_name["state"]._options = None -_SECRETVERSION._options = None -_REPLICATION_USERMANAGED.fields_by_name["replicas"]._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/secretmanager_v1/proto/resources_pb2_grpc.py b/google/cloud/secretmanager_v1/proto/resources_pb2_grpc.py deleted file mode 100644 index 8a93939..0000000 --- a/google/cloud/secretmanager_v1/proto/resources_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/secretmanager_v1/proto/service_pb2.py b/google/cloud/secretmanager_v1/proto/service_pb2.py deleted file mode 100644 index 0cb47e8..0000000 --- a/google/cloud/secretmanager_v1/proto/service_pb2.py +++ /dev/null @@ -1,1531 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/secretmanager_v1/proto/service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.secretmanager_v1.proto import ( - resources_pb2 as google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/secretmanager_v1/proto/service.proto", - package="google.cloud.secretmanager.v1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.secretmanager.v1B\014ServiceProtoP\001ZJgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1;secretmanager\370\001\001\242\002\003GSM\252\002\035Google.Cloud.SecretManager.V1\312\002\035Google\\Cloud\\SecretManager\\V1\352\002 Google::Cloud::SecretManager::V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n1google/cloud/secretmanager_v1/proto/service.proto\x12\x1dgoogle.cloud.secretmanager.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x33google/cloud/secretmanager_v1/proto/resources.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto"\x8a\x01\n\x12ListSecretsRequest\x12\x43\n\x06parent\x18\x01 \x01(\tB3\xe0\x41\x02\xfa\x41-\n+cloudresourcemanager.googleapis.com/Project\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01"z\n\x13ListSecretsResponse\x12\x36\n\x07secrets\x18\x01 \x03(\x0b\x32%.google.cloud.secretmanager.v1.Secret\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\x12\x12\n\ntotal_size\x18\x03 \x01(\x05"\xae\x01\n\x13\x43reateSecretRequest\x12\x43\n\x06parent\x18\x01 \x01(\tB3\xe0\x41\x02\xfa\x41-\n+cloudresourcemanager.googleapis.com/Project\x12\x16\n\tsecret_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12:\n\x06secret\x18\x03 \x01(\x0b\x32%.google.cloud.secretmanager.v1.SecretB\x03\xe0\x41\x02"\x9a\x01\n\x17\x41\x64\x64SecretVersionRequest\x12;\n\x06parent\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret\x12\x42\n\x07payload\x18\x02 \x01(\x0b\x32,.google.cloud.secretmanager.v1.SecretPayloadB\x03\xe0\x41\x02"M\n\x10GetSecretRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret"\x89\x01\n\x19ListSecretVersionsRequest\x12;\n\x06parent\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01"\x89\x01\n\x1aListSecretVersionsResponse\x12>\n\x08versions\x18\x01 \x03(\x0b\x32,.google.cloud.secretmanager.v1.SecretVersion\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\x12\x12\n\ntotal_size\x18\x03 \x01(\x05"[\n\x17GetSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"\x87\x01\n\x13UpdateSecretRequest\x12:\n\x06secret\x18\x01 \x01(\x0b\x32%.google.cloud.secretmanager.v1.SecretB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"^\n\x1a\x41\x63\x63\x65ssSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"\x9b\x01\n\x1b\x41\x63\x63\x65ssSecretVersionResponse\x12=\n\x04name\x18\x01 \x01(\tB/\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion\x12=\n\x07payload\x18\x02 \x01(\x0b\x32,.google.cloud.secretmanager.v1.SecretPayload"P\n\x13\x44\x65leteSecretRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret"_\n\x1b\x44isableSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"^\n\x1a\x45nableSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"_\n\x1b\x44\x65stroySecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion2\xcf\x15\n\x14SecretManagerService\x12\xa6\x01\n\x0bListSecrets\x12\x31.google.cloud.secretmanager.v1.ListSecretsRequest\x1a\x32.google.cloud.secretmanager.v1.ListSecretsResponse"0\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{parent=projects/*}/secrets\xda\x41\x06parent\x12\xb4\x01\n\x0c\x43reateSecret\x12\x32.google.cloud.secretmanager.v1.CreateSecretRequest\x1a%.google.cloud.secretmanager.v1.Secret"I\x82\xd3\xe4\x93\x02)"\x1f/v1/{parent=projects/*}/secrets:\x06secret\xda\x41\x17parent,secret_id,secret\x12\xc2\x01\n\x10\x41\x64\x64SecretVersion\x12\x36.google.cloud.secretmanager.v1.AddSecretVersionRequest\x1a,.google.cloud.secretmanager.v1.SecretVersion"H\x82\xd3\xe4\x93\x02\x31",/v1/{parent=projects/*/secrets/*}:addVersion:\x01*\xda\x41\x0eparent,payload\x12\x93\x01\n\tGetSecret\x12/.google.cloud.secretmanager.v1.GetSecretRequest\x1a%.google.cloud.secretmanager.v1.Secret".\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{name=projects/*/secrets/*}\xda\x41\x04name\x12\xb6\x01\n\x0cUpdateSecret\x12\x32.google.cloud.secretmanager.v1.UpdateSecretRequest\x1a%.google.cloud.secretmanager.v1.Secret"K\x82\xd3\xe4\x93\x02\x30\x32&/v1/{secret.name=projects/*/secrets/*}:\x06secret\xda\x41\x12secret,update_mask\x12\x8a\x01\n\x0c\x44\x65leteSecret\x12\x32.google.cloud.secretmanager.v1.DeleteSecretRequest\x1a\x16.google.protobuf.Empty".\x82\xd3\xe4\x93\x02!*\x1f/v1/{name=projects/*/secrets/*}\xda\x41\x04name\x12\xc6\x01\n\x12ListSecretVersions\x12\x38.google.cloud.secretmanager.v1.ListSecretVersionsRequest\x1a\x39.google.cloud.secretmanager.v1.ListSecretVersionsResponse";\x82\xd3\xe4\x93\x02,\x12*/v1/{parent=projects/*/secrets/*}/versions\xda\x41\x06parent\x12\xb3\x01\n\x10GetSecretVersion\x12\x36.google.cloud.secretmanager.v1.GetSecretVersionRequest\x1a,.google.cloud.secretmanager.v1.SecretVersion"9\x82\xd3\xe4\x93\x02,\x12*/v1/{name=projects/*/secrets/*/versions/*}\xda\x41\x04name\x12\xce\x01\n\x13\x41\x63\x63\x65ssSecretVersion\x12\x39.google.cloud.secretmanager.v1.AccessSecretVersionRequest\x1a:.google.cloud.secretmanager.v1.AccessSecretVersionResponse"@\x82\xd3\xe4\x93\x02\x33\x12\x31/v1/{name=projects/*/secrets/*/versions/*}:access\xda\x41\x04name\x12\xc6\x01\n\x14\x44isableSecretVersion\x12:.google.cloud.secretmanager.v1.DisableSecretVersionRequest\x1a,.google.cloud.secretmanager.v1.SecretVersion"D\x82\xd3\xe4\x93\x02\x37"2/v1/{name=projects/*/secrets/*/versions/*}:disable:\x01*\xda\x41\x04name\x12\xc3\x01\n\x13\x45nableSecretVersion\x12\x39.google.cloud.secretmanager.v1.EnableSecretVersionRequest\x1a,.google.cloud.secretmanager.v1.SecretVersion"C\x82\xd3\xe4\x93\x02\x36"1/v1/{name=projects/*/secrets/*/versions/*}:enable:\x01*\xda\x41\x04name\x12\xc6\x01\n\x14\x44\x65stroySecretVersion\x12:.google.cloud.secretmanager.v1.DestroySecretVersionRequest\x1a,.google.cloud.secretmanager.v1.SecretVersion"D\x82\xd3\xe4\x93\x02\x37"2/v1/{name=projects/*/secrets/*/versions/*}:destroy:\x01*\xda\x41\x04name\x12\x86\x01\n\x0cSetIamPolicy\x12".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy";\x82\xd3\xe4\x93\x02\x35"0/v1/{resource=projects/*/secrets/*}:setIamPolicy:\x01*\x12\x83\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"8\x82\xd3\xe4\x93\x02\x32\x12\x30/v1/{resource=projects/*/secrets/*}:getIamPolicy\x12\xac\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse"A\x82\xd3\xe4\x93\x02;"6/v1/{resource=projects/*/secrets/*}:testIamPermissions:\x01*\x1aP\xca\x41\x1csecretmanager.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xeb\x01\n!com.google.cloud.secretmanager.v1B\x0cServiceProtoP\x01ZJgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1;secretmanager\xf8\x01\x01\xa2\x02\x03GSM\xaa\x02\x1dGoogle.Cloud.SecretManager.V1\xca\x02\x1dGoogle\\Cloud\\SecretManager\\V1\xea\x02 Google::Cloud::SecretManager::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - ], -) - - -_LISTSECRETSREQUEST = _descriptor.Descriptor( - name="ListSecretsRequest", - full_name="google.cloud.secretmanager.v1.ListSecretsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secretmanager.v1.ListSecretsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A-\n+cloudresourcemanager.googleapis.com/Project", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.secretmanager.v1.ListSecretsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.secretmanager.v1.ListSecretsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=376, - serialized_end=514, -) - - -_LISTSECRETSRESPONSE = _descriptor.Descriptor( - name="ListSecretsResponse", - full_name="google.cloud.secretmanager.v1.ListSecretsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="secrets", - full_name="google.cloud.secretmanager.v1.ListSecretsResponse.secrets", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.secretmanager.v1.ListSecretsResponse.total_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=516, - serialized_end=638, -) - - -_CREATESECRETREQUEST = _descriptor.Descriptor( - name="CreateSecretRequest", - full_name="google.cloud.secretmanager.v1.CreateSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secretmanager.v1.CreateSecretRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A-\n+cloudresourcemanager.googleapis.com/Project", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="secret_id", - full_name="google.cloud.secretmanager.v1.CreateSecretRequest.secret_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="secret", - full_name="google.cloud.secretmanager.v1.CreateSecretRequest.secret", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=641, - serialized_end=815, -) - - -_ADDSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="AddSecretVersionRequest", - full_name="google.cloud.secretmanager.v1.AddSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secretmanager.v1.AddSecretVersionRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="payload", - full_name="google.cloud.secretmanager.v1.AddSecretVersionRequest.payload", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=818, - serialized_end=972, -) - - -_GETSECRETREQUEST = _descriptor.Descriptor( - name="GetSecretRequest", - full_name="google.cloud.secretmanager.v1.GetSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.GetSecretRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=974, - serialized_end=1051, -) - - -_LISTSECRETVERSIONSREQUEST = _descriptor.Descriptor( - name="ListSecretVersionsRequest", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1054, - serialized_end=1191, -) - - -_LISTSECRETVERSIONSRESPONSE = _descriptor.Descriptor( - name="ListSecretVersionsResponse", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="versions", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsResponse.versions", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.secretmanager.v1.ListSecretVersionsResponse.total_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1194, - serialized_end=1331, -) - - -_GETSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="GetSecretVersionRequest", - full_name="google.cloud.secretmanager.v1.GetSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.GetSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1333, - serialized_end=1424, -) - - -_UPDATESECRETREQUEST = _descriptor.Descriptor( - name="UpdateSecretRequest", - full_name="google.cloud.secretmanager.v1.UpdateSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="secret", - full_name="google.cloud.secretmanager.v1.UpdateSecretRequest.secret", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.secretmanager.v1.UpdateSecretRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1427, - serialized_end=1562, -) - - -_ACCESSSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="AccessSecretVersionRequest", - full_name="google.cloud.secretmanager.v1.AccessSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.AccessSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1564, - serialized_end=1658, -) - - -_ACCESSSECRETVERSIONRESPONSE = _descriptor.Descriptor( - name="AccessSecretVersionResponse", - full_name="google.cloud.secretmanager.v1.AccessSecretVersionResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.AccessSecretVersionResponse.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="payload", - full_name="google.cloud.secretmanager.v1.AccessSecretVersionResponse.payload", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1661, - serialized_end=1816, -) - - -_DELETESECRETREQUEST = _descriptor.Descriptor( - name="DeleteSecretRequest", - full_name="google.cloud.secretmanager.v1.DeleteSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.DeleteSecretRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1818, - serialized_end=1898, -) - - -_DISABLESECRETVERSIONREQUEST = _descriptor.Descriptor( - name="DisableSecretVersionRequest", - full_name="google.cloud.secretmanager.v1.DisableSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.DisableSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1900, - serialized_end=1995, -) - - -_ENABLESECRETVERSIONREQUEST = _descriptor.Descriptor( - name="EnableSecretVersionRequest", - full_name="google.cloud.secretmanager.v1.EnableSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.EnableSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1997, - serialized_end=2091, -) - - -_DESTROYSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="DestroySecretVersionRequest", - full_name="google.cloud.secretmanager.v1.DestroySecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secretmanager.v1.DestroySecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2093, - serialized_end=2188, -) - -_LISTSECRETSRESPONSE.fields_by_name[ - "secrets" -].message_type = ( - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRET -) -_CREATESECRETREQUEST.fields_by_name[ - "secret" -].message_type = ( - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRET -) -_ADDSECRETVERSIONREQUEST.fields_by_name[ - "payload" -].message_type = ( - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETPAYLOAD -) -_LISTSECRETVERSIONSRESPONSE.fields_by_name[ - "versions" -].message_type = ( - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETVERSION -) -_UPDATESECRETREQUEST.fields_by_name[ - "secret" -].message_type = ( - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRET -) -_UPDATESECRETREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_ACCESSSECRETVERSIONRESPONSE.fields_by_name[ - "payload" -].message_type = ( - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETPAYLOAD -) -DESCRIPTOR.message_types_by_name["ListSecretsRequest"] = _LISTSECRETSREQUEST -DESCRIPTOR.message_types_by_name["ListSecretsResponse"] = _LISTSECRETSRESPONSE -DESCRIPTOR.message_types_by_name["CreateSecretRequest"] = _CREATESECRETREQUEST -DESCRIPTOR.message_types_by_name["AddSecretVersionRequest"] = _ADDSECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name["GetSecretRequest"] = _GETSECRETREQUEST -DESCRIPTOR.message_types_by_name[ - "ListSecretVersionsRequest" -] = _LISTSECRETVERSIONSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListSecretVersionsResponse" -] = _LISTSECRETVERSIONSRESPONSE -DESCRIPTOR.message_types_by_name["GetSecretVersionRequest"] = _GETSECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name["UpdateSecretRequest"] = _UPDATESECRETREQUEST -DESCRIPTOR.message_types_by_name[ - "AccessSecretVersionRequest" -] = _ACCESSSECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name[ - "AccessSecretVersionResponse" -] = _ACCESSSECRETVERSIONRESPONSE -DESCRIPTOR.message_types_by_name["DeleteSecretRequest"] = _DELETESECRETREQUEST -DESCRIPTOR.message_types_by_name[ - "DisableSecretVersionRequest" -] = _DISABLESECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name[ - "EnableSecretVersionRequest" -] = _ENABLESECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name[ - "DestroySecretVersionRequest" -] = _DESTROYSECRETVERSIONREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListSecretsRequest = _reflection.GeneratedProtocolMessageType( - "ListSecretsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETSREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.ListSecrets][google.cloud.se - cretmanager.v1.SecretManagerService.ListSecrets]. - - Attributes: - parent: - Required. The resource name of the project associated with the - [Secrets][google.cloud.secretmanager.v1.Secret], in the format - ``projects/*``. - page_size: - Optional. The maximum number of results to be returned in a - single page. If set to 0, the server decides the number of - results to return. If the number is greater than 25000, it is - capped at 25000. - page_token: - Optional. Pagination token, returned earlier via [ListSecretsR - esponse.next_page_token][google.cloud.secretmanager.v1.ListSec - retsResponse.next_page_token]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.ListSecretsRequest) - }, -) -_sym_db.RegisterMessage(ListSecretsRequest) - -ListSecretsResponse = _reflection.GeneratedProtocolMessageType( - "ListSecretsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETSRESPONSE, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Response message for [SecretManagerService.ListSecrets][google.cloud.s - ecretmanager.v1.SecretManagerService.ListSecrets]. - - Attributes: - secrets: - The list of [Secrets][google.cloud.secretmanager.v1.Secret] - sorted in reverse by create_time (newest first). - next_page_token: - A token to retrieve the next page of results. Pass this value - in [ListSecretsRequest.page_token][google.cloud.secretmanager. - v1.ListSecretsRequest.page_token] to retrieve the next page. - total_size: - The total number of - [Secrets][google.cloud.secretmanager.v1.Secret]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.ListSecretsResponse) - }, -) -_sym_db.RegisterMessage(ListSecretsResponse) - -CreateSecretRequest = _reflection.GeneratedProtocolMessageType( - "CreateSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATESECRETREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.CreateSecret][google.cloud.s - ecretmanager.v1.SecretManagerService.CreateSecret]. - - Attributes: - parent: - Required. The resource name of the project to associate with - the [Secret][google.cloud.secretmanager.v1.Secret], in the - format ``projects/*``. - secret_id: - Required. This must be unique within the project. A secret ID - is a string with a maximum length of 255 characters and can - contain uppercase and lowercase letters, numerals, and the - hyphen (``-``) and underscore (``_``) characters. - secret: - Required. A [Secret][google.cloud.secretmanager.v1.Secret] - with initial field values. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.CreateSecretRequest) - }, -) -_sym_db.RegisterMessage(CreateSecretRequest) - -AddSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "AddSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _ADDSECRETVERSIONREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.AddSecretVersion][google.clo - ud.secretmanager.v1.SecretManagerService.AddSecretVersion]. - - Attributes: - parent: - Required. The resource name of the - [Secret][google.cloud.secretmanager.v1.Secret] to associate - with the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - in the format ``projects/*/secrets/*``. - payload: - Required. The secret payload of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.AddSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(AddSecretVersionRequest) - -GetSecretRequest = _reflection.GeneratedProtocolMessageType( - "GetSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSECRETREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.GetSecret][google.cloud.secr - etmanager.v1.SecretManagerService.GetSecret]. - - Attributes: - name: - Required. The resource name of the - [Secret][google.cloud.secretmanager.v1.Secret], in the format - ``projects/*/secrets/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.GetSecretRequest) - }, -) -_sym_db.RegisterMessage(GetSecretRequest) - -ListSecretVersionsRequest = _reflection.GeneratedProtocolMessageType( - "ListSecretVersionsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETVERSIONSREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.ListSecretVersions][google.c - loud.secretmanager.v1.SecretManagerService.ListSecretVersions]. - - Attributes: - parent: - Required. The resource name of the - [Secret][google.cloud.secretmanager.v1.Secret] associated with - the - [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] - to list, in the format ``projects/*/secrets/*``. - page_size: - Optional. The maximum number of results to be returned in a - single page. If set to 0, the server decides the number of - results to return. If the number is greater than 25000, it is - capped at 25000. - page_token: - Optional. Pagination token, returned earlier via - ListSecretVersionsResponse.next_page_token][]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.ListSecretVersionsRequest) - }, -) -_sym_db.RegisterMessage(ListSecretVersionsRequest) - -ListSecretVersionsResponse = _reflection.GeneratedProtocolMessageType( - "ListSecretVersionsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETVERSIONSRESPONSE, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Response message for [SecretManagerService.ListSecretVersions][google. - cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. - - Attributes: - versions: - The list of - [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] - sorted in reverse by create_time (newest first). - next_page_token: - A token to retrieve the next page of results. Pass this value - in [ListSecretVersionsRequest.page_token][google.cloud.secretm - anager.v1.ListSecretVersionsRequest.page_token] to retrieve - the next page. - total_size: - The total number of - [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.ListSecretVersionsResponse) - }, -) -_sym_db.RegisterMessage(ListSecretVersionsResponse) - -GetSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "GetSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSECRETVERSIONREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.GetSecretVersion][google.clo - ud.secretmanager.v1.SecretManagerService.GetSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - in the format ``projects/*/secrets/*/versions/*``. - ``projects/*/secrets/*/versions/latest`` is an alias to the - ``latest`` - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.GetSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(GetSecretVersionRequest) - -UpdateSecretRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESECRETREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.UpdateSecret][google.cloud.s - ecretmanager.v1.SecretManagerService.UpdateSecret]. - - Attributes: - secret: - Required. [Secret][google.cloud.secretmanager.v1.Secret] with - updated field values. - update_mask: - Required. Specifies the fields to be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.UpdateSecretRequest) - }, -) -_sym_db.RegisterMessage(UpdateSecretRequest) - -AccessSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "AccessSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _ACCESSSECRETVERSIONREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.AccessSecretVersion][google. - cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.AccessSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(AccessSecretVersionRequest) - -AccessSecretVersionResponse = _reflection.GeneratedProtocolMessageType( - "AccessSecretVersionResponse", - (_message.Message,), - { - "DESCRIPTOR": _ACCESSSECRETVERSIONRESPONSE, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Response message for [SecretManagerService.AccessSecretVersion][google - .cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. - - Attributes: - name: - The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - in the format ``projects/*/secrets/*/versions/*``. - payload: - Secret payload - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.AccessSecretVersionResponse) - }, -) -_sym_db.RegisterMessage(AccessSecretVersionResponse) - -DeleteSecretRequest = _reflection.GeneratedProtocolMessageType( - "DeleteSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETESECRETREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.DeleteSecret][google.cloud.s - ecretmanager.v1.SecretManagerService.DeleteSecret]. - - Attributes: - name: - Required. The resource name of the - [Secret][google.cloud.secretmanager.v1.Secret] to delete in - the format ``projects/*/secrets/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.DeleteSecretRequest) - }, -) -_sym_db.RegisterMessage(DeleteSecretRequest) - -DisableSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "DisableSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _DISABLESECRETVERSIONREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.DisableSecretVersion][google - .cloud.secretmanager.v1.SecretManagerService.DisableSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - to disable in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.DisableSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(DisableSecretVersionRequest) - -EnableSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "EnableSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _ENABLESECRETVERSIONREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.EnableSecretVersion][google. - cloud.secretmanager.v1.SecretManagerService.EnableSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - to enable in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.EnableSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(EnableSecretVersionRequest) - -DestroySecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "DestroySecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _DESTROYSECRETVERSIONREQUEST, - "__module__": "google.cloud.secretmanager_v1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.DestroySecretVersion][google - .cloud.secretmanager.v1.SecretManagerService.DestroySecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - to destroy in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.DestroySecretVersionRequest) - }, -) -_sym_db.RegisterMessage(DestroySecretVersionRequest) - - -DESCRIPTOR._options = None -_LISTSECRETSREQUEST.fields_by_name["parent"]._options = None -_LISTSECRETSREQUEST.fields_by_name["page_size"]._options = None -_LISTSECRETSREQUEST.fields_by_name["page_token"]._options = None -_CREATESECRETREQUEST.fields_by_name["parent"]._options = None -_CREATESECRETREQUEST.fields_by_name["secret_id"]._options = None -_CREATESECRETREQUEST.fields_by_name["secret"]._options = None -_ADDSECRETVERSIONREQUEST.fields_by_name["parent"]._options = None -_ADDSECRETVERSIONREQUEST.fields_by_name["payload"]._options = None -_GETSECRETREQUEST.fields_by_name["name"]._options = None -_LISTSECRETVERSIONSREQUEST.fields_by_name["parent"]._options = None -_LISTSECRETVERSIONSREQUEST.fields_by_name["page_size"]._options = None -_LISTSECRETVERSIONSREQUEST.fields_by_name["page_token"]._options = None -_GETSECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_UPDATESECRETREQUEST.fields_by_name["secret"]._options = None -_UPDATESECRETREQUEST.fields_by_name["update_mask"]._options = None -_ACCESSSECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_ACCESSSECRETVERSIONRESPONSE.fields_by_name["name"]._options = None -_DELETESECRETREQUEST.fields_by_name["name"]._options = None -_DISABLESECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_ENABLESECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_DESTROYSECRETVERSIONREQUEST.fields_by_name["name"]._options = None - -_SECRETMANAGERSERVICE = _descriptor.ServiceDescriptor( - name="SecretManagerService", - full_name="google.cloud.secretmanager.v1.SecretManagerService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\034secretmanager.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=2191, - serialized_end=4958, - methods=[ - _descriptor.MethodDescriptor( - name="ListSecrets", - full_name="google.cloud.secretmanager.v1.SecretManagerService.ListSecrets", - index=0, - containing_service=None, - input_type=_LISTSECRETSREQUEST, - output_type=_LISTSECRETSRESPONSE, - serialized_options=b"\202\323\344\223\002!\022\037/v1/{parent=projects/*}/secrets\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateSecret", - full_name="google.cloud.secretmanager.v1.SecretManagerService.CreateSecret", - index=1, - containing_service=None, - input_type=_CREATESECRETREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRET, - serialized_options=b'\202\323\344\223\002)"\037/v1/{parent=projects/*}/secrets:\006secret\332A\027parent,secret_id,secret', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AddSecretVersion", - full_name="google.cloud.secretmanager.v1.SecretManagerService.AddSecretVersion", - index=2, - containing_service=None, - input_type=_ADDSECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\0021",/v1/{parent=projects/*/secrets/*}:addVersion:\001*\332A\016parent,payload', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSecret", - full_name="google.cloud.secretmanager.v1.SecretManagerService.GetSecret", - index=3, - containing_service=None, - input_type=_GETSECRETREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRET, - serialized_options=b"\202\323\344\223\002!\022\037/v1/{name=projects/*/secrets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSecret", - full_name="google.cloud.secretmanager.v1.SecretManagerService.UpdateSecret", - index=4, - containing_service=None, - input_type=_UPDATESECRETREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRET, - serialized_options=b"\202\323\344\223\00202&/v1/{secret.name=projects/*/secrets/*}:\006secret\332A\022secret,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteSecret", - full_name="google.cloud.secretmanager.v1.SecretManagerService.DeleteSecret", - index=5, - containing_service=None, - input_type=_DELETESECRETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002!*\037/v1/{name=projects/*/secrets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListSecretVersions", - full_name="google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions", - index=6, - containing_service=None, - input_type=_LISTSECRETVERSIONSREQUEST, - output_type=_LISTSECRETVERSIONSRESPONSE, - serialized_options=b"\202\323\344\223\002,\022*/v1/{parent=projects/*/secrets/*}/versions\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSecretVersion", - full_name="google.cloud.secretmanager.v1.SecretManagerService.GetSecretVersion", - index=7, - containing_service=None, - input_type=_GETSECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b"\202\323\344\223\002,\022*/v1/{name=projects/*/secrets/*/versions/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AccessSecretVersion", - full_name="google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion", - index=8, - containing_service=None, - input_type=_ACCESSSECRETVERSIONREQUEST, - output_type=_ACCESSSECRETVERSIONRESPONSE, - serialized_options=b"\202\323\344\223\0023\0221/v1/{name=projects/*/secrets/*/versions/*}:access\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DisableSecretVersion", - full_name="google.cloud.secretmanager.v1.SecretManagerService.DisableSecretVersion", - index=9, - containing_service=None, - input_type=_DISABLESECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\0027"2/v1/{name=projects/*/secrets/*/versions/*}:disable:\001*\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="EnableSecretVersion", - full_name="google.cloud.secretmanager.v1.SecretManagerService.EnableSecretVersion", - index=10, - containing_service=None, - input_type=_ENABLESECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\0026"1/v1/{name=projects/*/secrets/*/versions/*}:enable:\001*\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DestroySecretVersion", - full_name="google.cloud.secretmanager.v1.SecretManagerService.DestroySecretVersion", - index=11, - containing_service=None, - input_type=_DESTROYSECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\0027"2/v1/{name=projects/*/secrets/*/versions/*}:destroy:\001*\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetIamPolicy", - full_name="google.cloud.secretmanager.v1.SecretManagerService.SetIamPolicy", - index=12, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._SETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\0025"0/v1/{resource=projects/*/secrets/*}:setIamPolicy:\001*', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetIamPolicy", - full_name="google.cloud.secretmanager.v1.SecretManagerService.GetIamPolicy", - index=13, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._GETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b"\202\323\344\223\0022\0220/v1/{resource=projects/*/secrets/*}:getIamPolicy", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="TestIamPermissions", - full_name="google.cloud.secretmanager.v1.SecretManagerService.TestIamPermissions", - index=14, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSREQUEST, - output_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSRESPONSE, - serialized_options=b'\202\323\344\223\002;"6/v1/{resource=projects/*/secrets/*}:testIamPermissions:\001*', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_SECRETMANAGERSERVICE) - -DESCRIPTOR.services_by_name["SecretManagerService"] = _SECRETMANAGERSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/secretmanager_v1/proto/service_pb2_grpc.py b/google/cloud/secretmanager_v1/proto/service_pb2_grpc.py deleted file mode 100644 index 75cf4f2..0000000 --- a/google/cloud/secretmanager_v1/proto/service_pb2_grpc.py +++ /dev/null @@ -1,761 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.secretmanager_v1.proto import ( - resources_pb2 as google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2, -) -from google.cloud.secretmanager_v1.proto import ( - service_pb2 as google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class SecretManagerServiceStub(object): - """`projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - * [Secret][google.cloud.secretmanager.v1.Secret] - * [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListSecrets = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretsResponse.FromString, - ) - self.CreateSecret = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/CreateSecret", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.CreateSecretRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.FromString, - ) - self.AddSecretVersion = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/AddSecretVersion", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AddSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.GetSecret = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/GetSecret", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.GetSecretRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.FromString, - ) - self.UpdateSecret = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/UpdateSecret", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.UpdateSecretRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.FromString, - ) - self.DeleteSecret = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/DeleteSecret", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DeleteSecretRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListSecretVersions = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/ListSecretVersions", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretVersionsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretVersionsResponse.FromString, - ) - self.GetSecretVersion = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/GetSecretVersion", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.GetSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.AccessSecretVersion = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AccessSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AccessSecretVersionResponse.FromString, - ) - self.DisableSecretVersion = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/DisableSecretVersion", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DisableSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.EnableSecretVersion = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/EnableSecretVersion", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.EnableSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.DestroySecretVersion = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/DestroySecretVersion", - request_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DestroySecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.SetIamPolicy = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/SetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.GetIamPolicy = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/GetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.TestIamPermissions = channel.unary_unary( - "/google.cloud.secretmanager.v1.SecretManagerService/TestIamPermissions", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - ) - - -class SecretManagerServiceServicer(object): - """`projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - * [Secret][google.cloud.secretmanager.v1.Secret] - * [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - """ - - def ListSecrets(self, request, context): - """Lists [Secrets][google.cloud.secretmanager.v1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateSecret(self, request, context): - """Creates a new [Secret][google.cloud.secretmanager.v1.Secret] containing no [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AddSecretVersion(self, request, context): - """Creates a new [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] containing secret data and attaches - it to an existing [Secret][google.cloud.secretmanager.v1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSecret(self, request, context): - """Gets metadata for a given [Secret][google.cloud.secretmanager.v1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSecret(self, request, context): - """Updates metadata of an existing [Secret][google.cloud.secretmanager.v1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteSecret(self, request, context): - """Deletes a [Secret][google.cloud.secretmanager.v1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListSecretVersions(self, request, context): - """Lists [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. This call does not return secret - data. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSecretVersion(self, request, context): - """Gets metadata for a [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - `projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AccessSecretVersion(self, request, context): - """Accesses a [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. This call returns the secret data. - - `projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DisableSecretVersion(self, request, context): - """Disables a [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Sets the [state][google.cloud.secretmanager.v1.SecretVersion.state] of the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] to - [DISABLED][google.cloud.secretmanager.v1.SecretVersion.State.DISABLED]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def EnableSecretVersion(self, request, context): - """Enables a [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Sets the [state][google.cloud.secretmanager.v1.SecretVersion.state] of the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] to - [ENABLED][google.cloud.secretmanager.v1.SecretVersion.State.ENABLED]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DestroySecretVersion(self, request, context): - """Destroys a [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Sets the [state][google.cloud.secretmanager.v1.SecretVersion.state] of the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] to - [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State.DESTROYED] and irrevocably destroys the - secret data. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetIamPolicy(self, request, context): - """Sets the access control policy on the specified secret. Replaces any - existing policy. - - Permissions on [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] are enforced according - to the policy set on the associated [Secret][google.cloud.secretmanager.v1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetIamPolicy(self, request, context): - """Gets the access control policy for a secret. - Returns empty policy if the secret exists and does not have a policy set. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def TestIamPermissions(self, request, context): - """Returns permissions that a caller has for the specified secret. - If the secret does not exist, this call returns an empty set of - permissions, not a NOT_FOUND error. - - Note: This operation is designed to be used for building permission-aware - UIs and command-line tools, not for authorization checking. This operation - may "fail open" without warning. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_SecretManagerServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListSecrets": grpc.unary_unary_rpc_method_handler( - servicer.ListSecrets, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretsRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretsResponse.SerializeToString, - ), - "CreateSecret": grpc.unary_unary_rpc_method_handler( - servicer.CreateSecret, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.CreateSecretRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.SerializeToString, - ), - "AddSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.AddSecretVersion, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AddSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "GetSecret": grpc.unary_unary_rpc_method_handler( - servicer.GetSecret, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.GetSecretRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.SerializeToString, - ), - "UpdateSecret": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSecret, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.UpdateSecretRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.SerializeToString, - ), - "DeleteSecret": grpc.unary_unary_rpc_method_handler( - servicer.DeleteSecret, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DeleteSecretRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListSecretVersions": grpc.unary_unary_rpc_method_handler( - servicer.ListSecretVersions, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretVersionsRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretVersionsResponse.SerializeToString, - ), - "GetSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.GetSecretVersion, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.GetSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "AccessSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.AccessSecretVersion, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AccessSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AccessSecretVersionResponse.SerializeToString, - ), - "DisableSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.DisableSecretVersion, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DisableSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "EnableSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.EnableSecretVersion, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.EnableSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "DestroySecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.DestroySecretVersion, - request_deserializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DestroySecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "SetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.SetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "GetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.GetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "TestIamPermissions": grpc.unary_unary_rpc_method_handler( - servicer.TestIamPermissions, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.secretmanager.v1.SecretManagerService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class SecretManagerService(object): - """`projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. - - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - * [Secret][google.cloud.secretmanager.v1.Secret] - * [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] - """ - - @staticmethod - def ListSecrets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretsRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/CreateSecret", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.CreateSecretRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AddSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/AddSecretVersion", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AddSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/GetSecret", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.GetSecretRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/UpdateSecret", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.UpdateSecretRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.Secret.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/DeleteSecret", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DeleteSecretRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListSecretVersions( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/ListSecretVersions", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretVersionsRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.ListSecretVersionsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/GetSecretVersion", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.GetSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AccessSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AccessSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.AccessSecretVersionResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DisableSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/DisableSecretVersion", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DisableSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def EnableSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/EnableSecretVersion", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.EnableSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DestroySecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/DestroySecretVersion", - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_service__pb2.DestroySecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secretmanager__v1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/SetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/GetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def TestIamPermissions( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secretmanager.v1.SecretManagerService/TestIamPermissions", - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/secretmanager_v1/py.typed b/google/cloud/secretmanager_v1/py.typed new file mode 100644 index 0000000..188cc03 --- /dev/null +++ b/google/cloud/secretmanager_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-secretmanager package uses inline types. diff --git a/google/__init__.py b/google/cloud/secretmanager_v1/services/__init__.py similarity index 71% rename from google/__init__.py rename to google/cloud/secretmanager_v1/services/__init__.py index 9a1b64a..42ffdf2 100644 --- a/google/__init__.py +++ b/google/cloud/secretmanager_v1/services/__init__.py @@ -1,24 +1,16 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - - __path__ = pkgutil.extend_path(__path__, __name__) +# diff --git a/google/cloud/secretmanager.py b/google/cloud/secretmanager_v1/services/secret_manager_service/__init__.py similarity index 68% rename from google/cloud/secretmanager.py rename to google/cloud/secretmanager_v1/services/secret_manager_service/__init__.py index f5b5f0d..5407ee8 100644 --- a/google/cloud/secretmanager.py +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/__init__.py @@ -1,29 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import - -from google.cloud.secretmanager_v1 import SecretManagerServiceClient -from google.cloud.secretmanager_v1 import enums -from google.cloud.secretmanager_v1 import types - +from .client import SecretManagerServiceClient +from .async_client import SecretManagerServiceAsyncClient __all__ = ( - "enums", - "types", "SecretManagerServiceClient", + "SecretManagerServiceAsyncClient", ) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py b/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py new file mode 100644 index 0000000..4cfce52 --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py @@ -0,0 +1,1423 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.secretmanager_v1.services.secret_manager_service import pagers +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport +from .client import SecretManagerServiceClient + + +class SecretManagerServiceAsyncClient: + """Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secretmanager.v1.Secret] + - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + """ + + _client: SecretManagerServiceClient + + DEFAULT_ENDPOINT = SecretManagerServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecretManagerServiceClient.DEFAULT_MTLS_ENDPOINT + + secret_path = staticmethod(SecretManagerServiceClient.secret_path) + parse_secret_path = staticmethod(SecretManagerServiceClient.parse_secret_path) + + from_service_account_file = SecretManagerServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecretManagerServiceClient).get_transport_class, + type(SecretManagerServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecretManagerServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the secret manager 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, ~.SecretManagerServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SecretManagerServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_secrets( + self, + request: service.ListSecretsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretsAsyncPager: + r"""Lists [Secrets][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.ListSecretsRequest`): + The request object. Request message for + [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. + parent (:class:`str`): + Required. The resource name of the project associated + with the + [Secrets][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretsAsyncPager: + Response message for + [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.ListSecretsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_secrets, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSecretsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_secret( + self, + request: service.CreateSecretRequest = None, + *, + parent: str = None, + secret_id: str = None, + secret: resources.Secret = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Creates a new [Secret][google.cloud.secretmanager.v1.Secret] + containing no + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + + Args: + request (:class:`~.service.CreateSecretRequest`): + The request object. Request message for + [SecretManagerService.CreateSecret][google.cloud.secretmanager.v1.SecretManagerService.CreateSecret]. + parent (:class:`str`): + Required. The resource name of the project to associate + with the [Secret][google.cloud.secretmanager.v1.Secret], + in the format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret_id (:class:`str`): + Required. This must be unique within the project. + + A secret ID is a string with a maximum length of 255 + characters and can contain uppercase and lowercase + letters, numerals, and the hyphen (``-``) and underscore + (``_``) characters. + This corresponds to the ``secret_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret (:class:`~.resources.Secret`): + Required. A + [Secret][google.cloud.secretmanager.v1.Secret] with + initial field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secretmanager.v1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, secret_id, secret]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.CreateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if secret_id is not None: + request.secret_id = secret_id + if secret is not None: + request.secret = secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def add_secret_version( + self, + request: service.AddSecretVersionRequest = None, + *, + parent: str = None, + payload: resources.SecretPayload = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Creates a new + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.AddSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AddSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AddSecretVersion]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to + associate with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`~.resources.SecretPayload`): + Required. The secret payload of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, payload]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.AddSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_secret( + self, + request: service.GetSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Gets metadata for a given + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.GetSecretRequest`): + The request object. Request message for + [SecretManagerService.GetSecret][google.cloud.secretmanager.v1.SecretManagerService.GetSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*/secrets/*``. + 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: + ~.resources.Secret: + A [Secret][google.cloud.secretmanager.v1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GetSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_secret( + self, + request: service.UpdateSecretRequest = None, + *, + secret: resources.Secret = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Updates metadata of an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.UpdateSecretRequest`): + The request object. Request message for + [SecretManagerService.UpdateSecret][google.cloud.secretmanager.v1.SecretManagerService.UpdateSecret]. + secret (:class:`~.resources.Secret`): + Required. [Secret][google.cloud.secretmanager.v1.Secret] + with updated field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Specifies the fields to be + updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secretmanager.v1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([secret, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.UpdateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if secret is not None: + request.secret = secret + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("secret.name", request.secret.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_secret( + self, + request: service.DeleteSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.DeleteSecretRequest`): + The request object. Request message for + [SecretManagerService.DeleteSecret][google.cloud.secretmanager.v1.SecretManagerService.DeleteSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to delete + in the format ``projects/*/secrets/*``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.DeleteSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_secret_versions( + self, + request: service.ListSecretVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretVersionsAsyncPager: + r"""Lists + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + This call does not return secret data. + + Args: + request (:class:`~.service.ListSecretVersionsRequest`): + The request object. Request message for + [SecretManagerService.ListSecretVersions][google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] + associated with the + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + to list, in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretVersionsAsyncPager: + Response message for + [SecretManagerService.ListSecretVersions][google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.ListSecretVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_secret_versions, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSecretVersionsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_secret_version( + self, + request: service.GetSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Gets metadata for a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Args: + request (:class:`~.service.GetSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.GetSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.GetSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + ``projects/*/secrets/*/versions/latest`` is an alias to + the ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GetSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def access_secret_version( + self, + request: service.AccessSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AccessSecretVersionResponse: + r"""Accesses a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Args: + request (:class:`~.service.AccessSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AccessSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + 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: + ~.service.AccessSecretVersionResponse: + Response message for + [SecretManagerService.AccessSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.AccessSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.access_secret_version, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Unknown, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def disable_secret_version( + self, + request: service.DisableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Disables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DISABLED][google.cloud.secretmanager.v1.SecretVersion.State.DISABLED]. + + Args: + request (:class:`~.service.DisableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DisableSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.DisableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to disable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.DisableSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.disable_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def enable_secret_version( + self, + request: service.EnableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Enables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [ENABLED][google.cloud.secretmanager.v1.SecretVersion.State.ENABLED]. + + Args: + request (:class:`~.service.EnableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.EnableSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.EnableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to enable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.EnableSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.enable_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def destroy_secret_version( + self, + request: service.DestroySecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Destroys a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Args: + request (:class:`~.service.DestroySecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DestroySecretVersion][google.cloud.secretmanager.v1.SecretManagerService.DestroySecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to destroy in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.DestroySecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.destroy_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + are enforced according to the policy set on the associated + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-secretmanager", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecretManagerServiceAsyncClient",) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/client.py b/google/cloud/secretmanager_v1/services/secret_manager_service/client.py new file mode 100644 index 0000000..22fcf07 --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/client.py @@ -0,0 +1,1586 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.secretmanager_v1.services.secret_manager_service import pagers +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecretManagerServiceGrpcTransport +from .transports.grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport + + +class SecretManagerServiceClientMeta(type): + """Metaclass for the SecretManagerService 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[SecretManagerServiceTransport]] + _transport_registry["grpc"] = SecretManagerServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SecretManagerServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[SecretManagerServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SecretManagerServiceClient(metaclass=SecretManagerServiceClientMeta): + """Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secretmanager.v1.Secret] + - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "secretmanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def secret_path(project: str, secret: str,) -> str: + """Return a fully-qualified secret string.""" + return "projects/{project}/secrets/{secret}".format( + project=project, secret=secret, + ) + + @staticmethod + def parse_secret_path(path: str) -> Dict[str, str]: + """Parse a secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecretManagerServiceTransport] = None, + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the secret manager 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, ~.SecretManagerServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + 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 = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecretManagerServiceTransport): + # transport is a SecretManagerServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_secrets( + self, + request: service.ListSecretsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretsPager: + r"""Lists [Secrets][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.ListSecretsRequest`): + The request object. Request message for + [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. + parent (:class:`str`): + Required. The resource name of the project associated + with the + [Secrets][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretsPager: + Response message for + [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. + + 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 service.ListSecretsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSecretsRequest): + request = service.ListSecretsRequest(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_secrets] + + # Certain fields should be provided 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.ListSecretsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def create_secret( + self, + request: service.CreateSecretRequest = None, + *, + parent: str = None, + secret_id: str = None, + secret: resources.Secret = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Creates a new [Secret][google.cloud.secretmanager.v1.Secret] + containing no + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + + Args: + request (:class:`~.service.CreateSecretRequest`): + The request object. Request message for + [SecretManagerService.CreateSecret][google.cloud.secretmanager.v1.SecretManagerService.CreateSecret]. + parent (:class:`str`): + Required. The resource name of the project to associate + with the [Secret][google.cloud.secretmanager.v1.Secret], + in the format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret_id (:class:`str`): + Required. This must be unique within the project. + + A secret ID is a string with a maximum length of 255 + characters and can contain uppercase and lowercase + letters, numerals, and the hyphen (``-``) and underscore + (``_``) characters. + This corresponds to the ``secret_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret (:class:`~.resources.Secret`): + Required. A + [Secret][google.cloud.secretmanager.v1.Secret] with + initial field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secretmanager.v1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, secret_id, secret]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.CreateSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecretRequest): + request = service.CreateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if secret_id is not None: + request.secret_id = secret_id + if secret is not None: + request.secret = secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secret] + + # Certain fields should be provided 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 add_secret_version( + self, + request: service.AddSecretVersionRequest = None, + *, + parent: str = None, + payload: resources.SecretPayload = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Creates a new + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.AddSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AddSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AddSecretVersion]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to + associate with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`~.resources.SecretPayload`): + Required. The secret payload of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, payload]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.AddSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.AddSecretVersionRequest): + request = service.AddSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_secret_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_secret( + self, + request: service.GetSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Gets metadata for a given + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.GetSecretRequest`): + The request object. Request message for + [SecretManagerService.GetSecret][google.cloud.secretmanager.v1.SecretManagerService.GetSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*/secrets/*``. + 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: + ~.resources.Secret: + A [Secret][google.cloud.secretmanager.v1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetSecretRequest): + request = service.GetSecretRequest(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_secret] + + # 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 update_secret( + self, + request: service.UpdateSecretRequest = None, + *, + secret: resources.Secret = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Updates metadata of an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.UpdateSecretRequest`): + The request object. Request message for + [SecretManagerService.UpdateSecret][google.cloud.secretmanager.v1.SecretManagerService.UpdateSecret]. + secret (:class:`~.resources.Secret`): + Required. [Secret][google.cloud.secretmanager.v1.Secret] + with updated field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Specifies the fields to be + updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secretmanager.v1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([secret, 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 service.UpdateSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateSecretRequest): + request = service.UpdateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if secret is not None: + request.secret = secret + 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_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("secret.name", request.secret.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_secret( + self, + request: service.DeleteSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.service.DeleteSecretRequest`): + The request object. Request message for + [SecretManagerService.DeleteSecret][google.cloud.secretmanager.v1.SecretManagerService.DeleteSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to delete + in the format ``projects/*/secrets/*``. + 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 service.DeleteSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteSecretRequest): + request = service.DeleteSecretRequest(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_secret] + + # 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 list_secret_versions( + self, + request: service.ListSecretVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretVersionsPager: + r"""Lists + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + This call does not return secret data. + + Args: + request (:class:`~.service.ListSecretVersionsRequest`): + The request object. Request message for + [SecretManagerService.ListSecretVersions][google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] + associated with the + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + to list, in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretVersionsPager: + Response message for + [SecretManagerService.ListSecretVersions][google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. + + 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 service.ListSecretVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSecretVersionsRequest): + request = service.ListSecretVersionsRequest(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_secret_versions] + + # Certain fields should be provided 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.ListSecretVersionsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_secret_version( + self, + request: service.GetSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Gets metadata for a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Args: + request (:class:`~.service.GetSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.GetSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.GetSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + ``projects/*/secrets/*/versions/latest`` is an alias to + the ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetSecretVersionRequest): + request = service.GetSecretVersionRequest(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_secret_version] + + # 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 access_secret_version( + self, + request: service.AccessSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AccessSecretVersionResponse: + r"""Accesses a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Args: + request (:class:`~.service.AccessSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AccessSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + 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: + ~.service.AccessSecretVersionResponse: + Response message for + [SecretManagerService.AccessSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.AccessSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.AccessSecretVersionRequest): + request = service.AccessSecretVersionRequest(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.access_secret_version] + + # 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 disable_secret_version( + self, + request: service.DisableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Disables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DISABLED][google.cloud.secretmanager.v1.SecretVersion.State.DISABLED]. + + Args: + request (:class:`~.service.DisableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DisableSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.DisableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to disable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.DisableSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DisableSecretVersionRequest): + request = service.DisableSecretVersionRequest(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.disable_secret_version] + + # 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 enable_secret_version( + self, + request: service.EnableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Enables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [ENABLED][google.cloud.secretmanager.v1.SecretVersion.State.ENABLED]. + + Args: + request (:class:`~.service.EnableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.EnableSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.EnableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to enable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.EnableSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.EnableSecretVersionRequest): + request = service.EnableSecretVersionRequest(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.enable_secret_version] + + # 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 destroy_secret_version( + self, + request: service.DestroySecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Destroys a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Args: + request (:class:`~.service.DestroySecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DestroySecretVersion][google.cloud.secretmanager.v1.SecretManagerService.DestroySecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to destroy in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.DestroySecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DestroySecretVersionRequest): + request = service.DestroySecretVersionRequest(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.destroy_secret_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + are enforced according to the policy set on the associated + [Secret][google.cloud.secretmanager.v1.Secret]. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-secretmanager", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecretManagerServiceClient",) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/pagers.py b/google/cloud/secretmanager_v1/services/secret_manager_service/pagers.py new file mode 100644 index 0000000..0a8238b --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/pagers.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service + + +class ListSecretsPager: + """A pager for iterating through ``list_secrets`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``secrets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecrets`` requests and continue to iterate + through the ``secrets`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretsResponse` + 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[..., service.ListSecretsResponse], + request: service.ListSecretsRequest, + response: service.ListSecretsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretsRequest`): + The initial request object. + response (:class:`~.service.ListSecretsResponse`): + 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 = service.ListSecretsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[service.ListSecretsResponse]: + 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[resources.Secret]: + for page in self.pages: + yield from page.secrets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecretsAsyncPager: + """A pager for iterating through ``list_secrets`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``secrets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecrets`` requests and continue to iterate + through the ``secrets`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListSecretsResponse]], + request: service.ListSecretsRequest, + response: service.ListSecretsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretsRequest`): + The initial request object. + response (:class:`~.service.ListSecretsResponse`): + 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 = service.ListSecretsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[service.ListSecretsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[resources.Secret]: + async def async_generator(): + async for page in self.pages: + for response in page.secrets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecretVersionsPager: + """A pager for iterating through ``list_secret_versions`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecretVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretVersionsResponse` + 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[..., service.ListSecretVersionsResponse], + request: service.ListSecretVersionsRequest, + response: service.ListSecretVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretVersionsRequest`): + The initial request object. + response (:class:`~.service.ListSecretVersionsResponse`): + 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 = service.ListSecretVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[service.ListSecretVersionsResponse]: + 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[resources.SecretVersion]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecretVersionsAsyncPager: + """A pager for iterating through ``list_secret_versions`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecretVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListSecretVersionsResponse]], + request: service.ListSecretVersionsRequest, + response: service.ListSecretVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretVersionsRequest`): + The initial request object. + response (:class:`~.service.ListSecretVersionsResponse`): + 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 = service.ListSecretVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[service.ListSecretVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[resources.SecretVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/transports/__init__.py b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/__init__.py new file mode 100644 index 0000000..71c2343 --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SecretManagerServiceTransport +from .grpc import SecretManagerServiceGrpcTransport +from .grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SecretManagerServiceTransport]] +_transport_registry["grpc"] = SecretManagerServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SecretManagerServiceGrpcAsyncIOTransport + + +__all__ = ( + "SecretManagerServiceTransport", + "SecretManagerServiceGrpcTransport", + "SecretManagerServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py new file mode 100644 index 0000000..e065202 --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-secretmanager", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SecretManagerServiceTransport(abc.ABC): + """Abstract transport class for SecretManagerService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_secrets: gapic_v1.method.wrap_method( + self.list_secrets, default_timeout=60.0, client_info=client_info, + ), + self.create_secret: gapic_v1.method.wrap_method( + self.create_secret, default_timeout=60.0, client_info=client_info, + ), + self.add_secret_version: gapic_v1.method.wrap_method( + self.add_secret_version, default_timeout=60.0, client_info=client_info, + ), + self.get_secret: gapic_v1.method.wrap_method( + self.get_secret, default_timeout=60.0, client_info=client_info, + ), + self.update_secret: gapic_v1.method.wrap_method( + self.update_secret, default_timeout=60.0, client_info=client_info, + ), + self.delete_secret: gapic_v1.method.wrap_method( + self.delete_secret, default_timeout=60.0, client_info=client_info, + ), + self.list_secret_versions: gapic_v1.method.wrap_method( + self.list_secret_versions, + default_timeout=60.0, + client_info=client_info, + ), + self.get_secret_version: gapic_v1.method.wrap_method( + self.get_secret_version, default_timeout=60.0, client_info=client_info, + ), + self.access_secret_version: gapic_v1.method.wrap_method( + self.access_secret_version, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Unknown, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_secret_version: gapic_v1.method.wrap_method( + self.disable_secret_version, + default_timeout=60.0, + client_info=client_info, + ), + self.enable_secret_version: gapic_v1.method.wrap_method( + self.enable_secret_version, + default_timeout=60.0, + client_info=client_info, + ), + self.destroy_secret_version: gapic_v1.method.wrap_method( + self.destroy_secret_version, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, default_timeout=60.0, client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, default_timeout=60.0, client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=60.0, + client_info=client_info, + ), + } + + @property + def list_secrets( + self, + ) -> typing.Callable[ + [service.ListSecretsRequest], + typing.Union[ + service.ListSecretsResponse, typing.Awaitable[service.ListSecretsResponse] + ], + ]: + raise NotImplementedError() + + @property + def create_secret( + self, + ) -> typing.Callable[ + [service.CreateSecretRequest], + typing.Union[resources.Secret, typing.Awaitable[resources.Secret]], + ]: + raise NotImplementedError() + + @property + def add_secret_version( + self, + ) -> typing.Callable[ + [service.AddSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def get_secret( + self, + ) -> typing.Callable[ + [service.GetSecretRequest], + typing.Union[resources.Secret, typing.Awaitable[resources.Secret]], + ]: + raise NotImplementedError() + + @property + def update_secret( + self, + ) -> typing.Callable[ + [service.UpdateSecretRequest], + typing.Union[resources.Secret, typing.Awaitable[resources.Secret]], + ]: + raise NotImplementedError() + + @property + def delete_secret( + self, + ) -> typing.Callable[ + [service.DeleteSecretRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_secret_versions( + self, + ) -> typing.Callable[ + [service.ListSecretVersionsRequest], + typing.Union[ + service.ListSecretVersionsResponse, + typing.Awaitable[service.ListSecretVersionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_secret_version( + self, + ) -> typing.Callable[ + [service.GetSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def access_secret_version( + self, + ) -> typing.Callable[ + [service.AccessSecretVersionRequest], + typing.Union[ + service.AccessSecretVersionResponse, + typing.Awaitable[service.AccessSecretVersionResponse], + ], + ]: + raise NotImplementedError() + + @property + def disable_secret_version( + self, + ) -> typing.Callable[ + [service.DisableSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def enable_secret_version( + self, + ) -> typing.Callable[ + [service.EnableSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def destroy_secret_version( + self, + ) -> typing.Callable[ + [service.DestroySecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecretManagerServiceTransport",) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py new file mode 100644 index 0000000..a92701e --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py @@ -0,0 +1,692 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO + + +class SecretManagerServiceGrpcTransport(SecretManagerServiceTransport): + """gRPC backend transport for SecretManagerService. + + Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secretmanager.v1.Secret] + - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_secrets( + self, + ) -> Callable[[service.ListSecretsRequest], service.ListSecretsResponse]: + r"""Return a callable for the list secrets method over gRPC. + + Lists [Secrets][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.ListSecretsRequest], + ~.ListSecretsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secrets" not in self._stubs: + self._stubs["list_secrets"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets", + request_serializer=service.ListSecretsRequest.serialize, + response_deserializer=service.ListSecretsResponse.deserialize, + ) + return self._stubs["list_secrets"] + + @property + def create_secret( + self, + ) -> Callable[[service.CreateSecretRequest], resources.Secret]: + r"""Return a callable for the create secret method over gRPC. + + Creates a new [Secret][google.cloud.secretmanager.v1.Secret] + containing no + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + + Returns: + Callable[[~.CreateSecretRequest], + ~.Secret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_secret" not in self._stubs: + self._stubs["create_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/CreateSecret", + request_serializer=service.CreateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["create_secret"] + + @property + def add_secret_version( + self, + ) -> Callable[[service.AddSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the add secret version method over gRPC. + + Creates a new + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.AddSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_secret_version" not in self._stubs: + self._stubs["add_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/AddSecretVersion", + request_serializer=service.AddSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["add_secret_version"] + + @property + def get_secret(self) -> Callable[[service.GetSecretRequest], resources.Secret]: + r"""Return a callable for the get secret method over gRPC. + + Gets metadata for a given + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.GetSecretRequest], + ~.Secret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret" not in self._stubs: + self._stubs["get_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/GetSecret", + request_serializer=service.GetSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["get_secret"] + + @property + def update_secret( + self, + ) -> Callable[[service.UpdateSecretRequest], resources.Secret]: + r"""Return a callable for the update secret method over gRPC. + + Updates metadata of an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.UpdateSecretRequest], + ~.Secret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_secret" not in self._stubs: + self._stubs["update_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/UpdateSecret", + request_serializer=service.UpdateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["update_secret"] + + @property + def delete_secret(self) -> Callable[[service.DeleteSecretRequest], empty.Empty]: + r"""Return a callable for the delete secret method over gRPC. + + Deletes a [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.DeleteSecretRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_secret" not in self._stubs: + self._stubs["delete_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/DeleteSecret", + request_serializer=service.DeleteSecretRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_secret"] + + @property + def list_secret_versions( + self, + ) -> Callable[ + [service.ListSecretVersionsRequest], service.ListSecretVersionsResponse + ]: + r"""Return a callable for the list secret versions method over gRPC. + + Lists + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + This call does not return secret data. + + Returns: + Callable[[~.ListSecretVersionsRequest], + ~.ListSecretVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secret_versions" not in self._stubs: + self._stubs["list_secret_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/ListSecretVersions", + request_serializer=service.ListSecretVersionsRequest.serialize, + response_deserializer=service.ListSecretVersionsResponse.deserialize, + ) + return self._stubs["list_secret_versions"] + + @property + def get_secret_version( + self, + ) -> Callable[[service.GetSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the get secret version method over gRPC. + + Gets metadata for a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Returns: + Callable[[~.GetSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret_version" not in self._stubs: + self._stubs["get_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/GetSecretVersion", + request_serializer=service.GetSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["get_secret_version"] + + @property + def access_secret_version( + self, + ) -> Callable[ + [service.AccessSecretVersionRequest], service.AccessSecretVersionResponse + ]: + r"""Return a callable for the access secret version method over gRPC. + + Accesses a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Returns: + Callable[[~.AccessSecretVersionRequest], + ~.AccessSecretVersionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "access_secret_version" not in self._stubs: + self._stubs["access_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion", + request_serializer=service.AccessSecretVersionRequest.serialize, + response_deserializer=service.AccessSecretVersionResponse.deserialize, + ) + return self._stubs["access_secret_version"] + + @property + def disable_secret_version( + self, + ) -> Callable[[service.DisableSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the disable secret version method over gRPC. + + Disables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DISABLED][google.cloud.secretmanager.v1.SecretVersion.State.DISABLED]. + + Returns: + Callable[[~.DisableSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_secret_version" not in self._stubs: + self._stubs["disable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/DisableSecretVersion", + request_serializer=service.DisableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["disable_secret_version"] + + @property + def enable_secret_version( + self, + ) -> Callable[[service.EnableSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the enable secret version method over gRPC. + + Enables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [ENABLED][google.cloud.secretmanager.v1.SecretVersion.State.ENABLED]. + + Returns: + Callable[[~.EnableSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_secret_version" not in self._stubs: + self._stubs["enable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/EnableSecretVersion", + request_serializer=service.EnableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["enable_secret_version"] + + @property + def destroy_secret_version( + self, + ) -> Callable[[service.DestroySecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the destroy secret version method over gRPC. + + Destroys a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Returns: + Callable[[~.DestroySecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "destroy_secret_version" not in self._stubs: + self._stubs["destroy_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/DestroySecretVersion", + request_serializer=service.DestroySecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["destroy_secret_version"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + are enforced according to the policy set on the associated + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SecretManagerServiceGrpcTransport",) diff --git a/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..069345d --- /dev/null +++ b/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py @@ -0,0 +1,709 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SecretManagerServiceGrpcTransport + + +class SecretManagerServiceGrpcAsyncIOTransport(SecretManagerServiceTransport): + """gRPC AsyncIO backend transport for SecretManagerService. + + Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secretmanager.v1.Secret] + - [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_secrets( + self, + ) -> Callable[[service.ListSecretsRequest], Awaitable[service.ListSecretsResponse]]: + r"""Return a callable for the list secrets method over gRPC. + + Lists [Secrets][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.ListSecretsRequest], + Awaitable[~.ListSecretsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secrets" not in self._stubs: + self._stubs["list_secrets"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets", + request_serializer=service.ListSecretsRequest.serialize, + response_deserializer=service.ListSecretsResponse.deserialize, + ) + return self._stubs["list_secrets"] + + @property + def create_secret( + self, + ) -> Callable[[service.CreateSecretRequest], Awaitable[resources.Secret]]: + r"""Return a callable for the create secret method over gRPC. + + Creates a new [Secret][google.cloud.secretmanager.v1.Secret] + containing no + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + + Returns: + Callable[[~.CreateSecretRequest], + Awaitable[~.Secret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_secret" not in self._stubs: + self._stubs["create_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/CreateSecret", + request_serializer=service.CreateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["create_secret"] + + @property + def add_secret_version( + self, + ) -> Callable[ + [service.AddSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the add secret version method over gRPC. + + Creates a new + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.AddSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_secret_version" not in self._stubs: + self._stubs["add_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/AddSecretVersion", + request_serializer=service.AddSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["add_secret_version"] + + @property + def get_secret( + self, + ) -> Callable[[service.GetSecretRequest], Awaitable[resources.Secret]]: + r"""Return a callable for the get secret method over gRPC. + + Gets metadata for a given + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.GetSecretRequest], + Awaitable[~.Secret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret" not in self._stubs: + self._stubs["get_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/GetSecret", + request_serializer=service.GetSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["get_secret"] + + @property + def update_secret( + self, + ) -> Callable[[service.UpdateSecretRequest], Awaitable[resources.Secret]]: + r"""Return a callable for the update secret method over gRPC. + + Updates metadata of an existing + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.UpdateSecretRequest], + Awaitable[~.Secret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_secret" not in self._stubs: + self._stubs["update_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/UpdateSecret", + request_serializer=service.UpdateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["update_secret"] + + @property + def delete_secret( + self, + ) -> Callable[[service.DeleteSecretRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete secret method over gRPC. + + Deletes a [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.DeleteSecretRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_secret" not in self._stubs: + self._stubs["delete_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/DeleteSecret", + request_serializer=service.DeleteSecretRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_secret"] + + @property + def list_secret_versions( + self, + ) -> Callable[ + [service.ListSecretVersionsRequest], + Awaitable[service.ListSecretVersionsResponse], + ]: + r"""Return a callable for the list secret versions method over gRPC. + + Lists + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + This call does not return secret data. + + Returns: + Callable[[~.ListSecretVersionsRequest], + Awaitable[~.ListSecretVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secret_versions" not in self._stubs: + self._stubs["list_secret_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/ListSecretVersions", + request_serializer=service.ListSecretVersionsRequest.serialize, + response_deserializer=service.ListSecretVersionsResponse.deserialize, + ) + return self._stubs["list_secret_versions"] + + @property + def get_secret_version( + self, + ) -> Callable[ + [service.GetSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the get secret version method over gRPC. + + Gets metadata for a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Returns: + Callable[[~.GetSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret_version" not in self._stubs: + self._stubs["get_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/GetSecretVersion", + request_serializer=service.GetSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["get_secret_version"] + + @property + def access_secret_version( + self, + ) -> Callable[ + [service.AccessSecretVersionRequest], + Awaitable[service.AccessSecretVersionResponse], + ]: + r"""Return a callable for the access secret version method over gRPC. + + Accesses a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Returns: + Callable[[~.AccessSecretVersionRequest], + Awaitable[~.AccessSecretVersionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "access_secret_version" not in self._stubs: + self._stubs["access_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion", + request_serializer=service.AccessSecretVersionRequest.serialize, + response_deserializer=service.AccessSecretVersionResponse.deserialize, + ) + return self._stubs["access_secret_version"] + + @property + def disable_secret_version( + self, + ) -> Callable[ + [service.DisableSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the disable secret version method over gRPC. + + Disables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DISABLED][google.cloud.secretmanager.v1.SecretVersion.State.DISABLED]. + + Returns: + Callable[[~.DisableSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_secret_version" not in self._stubs: + self._stubs["disable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/DisableSecretVersion", + request_serializer=service.DisableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["disable_secret_version"] + + @property + def enable_secret_version( + self, + ) -> Callable[ + [service.EnableSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the enable secret version method over gRPC. + + Enables a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [ENABLED][google.cloud.secretmanager.v1.SecretVersion.State.ENABLED]. + + Returns: + Callable[[~.EnableSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_secret_version" not in self._stubs: + self._stubs["enable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/EnableSecretVersion", + request_serializer=service.EnableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["enable_secret_version"] + + @property + def destroy_secret_version( + self, + ) -> Callable[ + [service.DestroySecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the destroy secret version method over gRPC. + + Destroys a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Sets the + [state][google.cloud.secretmanager.v1.SecretVersion.state] of + the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to + [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Returns: + Callable[[~.DestroySecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "destroy_secret_version" not in self._stubs: + self._stubs["destroy_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/DestroySecretVersion", + request_serializer=service.DestroySecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["destroy_secret_version"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + are enforced according to the policy set on the associated + [Secret][google.cloud.secretmanager.v1.Secret]. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SecretManagerServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/secretmanager_v1/types.py b/google/cloud/secretmanager_v1/types.py deleted file mode 100644 index c66de11..0000000 --- a/google/cloud/secretmanager_v1/types.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.secretmanager_v1.proto import resources_pb2 -from google.cloud.secretmanager_v1.proto import service_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - iam_policy_pb2, - options_pb2, - policy_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - expr_pb2, -] - -_local_modules = [ - resources_pb2, - service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.secretmanager_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/secretmanager_v1/types/__init__.py b/google/cloud/secretmanager_v1/types/__init__.py new file mode 100644 index 0000000..3a0ef41 --- /dev/null +++ b/google/cloud/secretmanager_v1/types/__init__.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .resources import ( + Secret, + SecretVersion, + Replication, + CustomerManagedEncryption, + ReplicationStatus, + CustomerManagedEncryptionStatus, + SecretPayload, +) +from .service import ( + ListSecretsRequest, + ListSecretsResponse, + CreateSecretRequest, + AddSecretVersionRequest, + GetSecretRequest, + ListSecretVersionsRequest, + ListSecretVersionsResponse, + GetSecretVersionRequest, + UpdateSecretRequest, + AccessSecretVersionRequest, + AccessSecretVersionResponse, + DeleteSecretRequest, + DisableSecretVersionRequest, + EnableSecretVersionRequest, + DestroySecretVersionRequest, +) + + +__all__ = ( + "Secret", + "SecretVersion", + "Replication", + "CustomerManagedEncryption", + "ReplicationStatus", + "CustomerManagedEncryptionStatus", + "SecretPayload", + "ListSecretsRequest", + "ListSecretsResponse", + "CreateSecretRequest", + "AddSecretVersionRequest", + "GetSecretRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "GetSecretVersionRequest", + "UpdateSecretRequest", + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "DeleteSecretRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "DestroySecretVersionRequest", +) diff --git a/google/cloud/secretmanager_v1/types/resources.py b/google/cloud/secretmanager_v1/types/resources.py new file mode 100644 index 0000000..b94f55d --- /dev/null +++ b/google/cloud/secretmanager_v1/types/resources.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.secretmanager.v1", + manifest={ + "Secret", + "SecretVersion", + "Replication", + "CustomerManagedEncryption", + "ReplicationStatus", + "CustomerManagedEncryptionStatus", + "SecretPayload", + }, +) + + +class Secret(proto.Message): + r"""A [Secret][google.cloud.secretmanager.v1.Secret] is a logical secret + whose value and versions can be accessed. + + A [Secret][google.cloud.secretmanager.v1.Secret] is made up of zero + or more + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] that + represent the secret data. + + Attributes: + name (str): + Output only. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] in the format + ``projects/*/secrets/*``. + replication (~.resources.Replication): + Required. Immutable. The replication policy of the secret + data attached to the + [Secret][google.cloud.secretmanager.v1.Secret]. + + The replication policy cannot be changed after the Secret + has been created. + create_time (~.timestamp.Timestamp): + Output only. The time at which the + [Secret][google.cloud.secretmanager.v1.Secret] was created. + labels (Sequence[~.resources.Secret.LabelsEntry]): + The labels assigned to this Secret. + + Label keys must be between 1 and 63 characters long, have a + UTF-8 encoding of maximum 128 bytes, and must conform to the + following PCRE regular expression: + ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}`` + + Label values must be between 0 and 63 characters long, have + a UTF-8 encoding of maximum 128 bytes, and must conform to + the following PCRE regular expression: + ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}`` + + No more than 64 labels can be assigned to a given resource. + """ + + name = proto.Field(proto.STRING, number=1) + + replication = proto.Field(proto.MESSAGE, number=2, message="Replication",) + + create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + labels = proto.MapField(proto.STRING, proto.STRING, number=4) + + +class SecretVersion(proto.Message): + r"""A secret version resource in the Secret Manager API. + + Attributes: + name (str): + Output only. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + IDs in a [Secret][google.cloud.secretmanager.v1.Secret] + start at 1 and are incremented for each subsequent version + of the secret. + create_time (~.timestamp.Timestamp): + Output only. The time at which the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + was created. + destroy_time (~.timestamp.Timestamp): + Output only. The time this + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + was destroyed. Only present if + [state][google.cloud.secretmanager.v1.SecretVersion.state] + is + [DESTROYED][google.cloud.secretmanager.v1.SecretVersion.State.DESTROYED]. + state (~.resources.SecretVersion.State): + Output only. The current state of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + replication_status (~.resources.ReplicationStatus): + The replication status of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + """ + + class State(proto.Enum): + r"""The state of a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion], + indicating if it can be accessed. + """ + STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + DESTROYED = 3 + + name = proto.Field(proto.STRING, number=1) + + create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + destroy_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + replication_status = proto.Field( + proto.MESSAGE, number=5, message="ReplicationStatus", + ) + + +class Replication(proto.Message): + r"""A policy that defines the replication and encryption + configuration of data. + + Attributes: + automatic (~.resources.Replication.Automatic): + The [Secret][google.cloud.secretmanager.v1.Secret] will + automatically be replicated without any restrictions. + user_managed (~.resources.Replication.UserManaged): + The [Secret][google.cloud.secretmanager.v1.Secret] will only + be replicated into the locations specified. + """ + + class Automatic(proto.Message): + r"""A replication policy that replicates the + [Secret][google.cloud.secretmanager.v1.Secret] payload without any + restrictions. + + Attributes: + customer_managed_encryption (~.resources.CustomerManagedEncryption): + Optional. The customer-managed encryption configuration of + the [Secret][google.cloud.secretmanager.v1.Secret]. If no + configuration is provided, Google-managed default encryption + is used. + + Updates to the + [Secret][google.cloud.secretmanager.v1.Secret] encryption + configuration only apply to + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + added afterwards. They do not apply retroactively to + existing + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + """ + + customer_managed_encryption = proto.Field( + proto.MESSAGE, number=1, message="CustomerManagedEncryption", + ) + + class UserManaged(proto.Message): + r"""A replication policy that replicates the + [Secret][google.cloud.secretmanager.v1.Secret] payload into the + locations specified in [Secret.replication.user_managed.replicas][] + + Attributes: + replicas (Sequence[~.resources.Replication.UserManaged.Replica]): + Required. The list of Replicas for this + [Secret][google.cloud.secretmanager.v1.Secret]. + + Cannot be empty. + """ + + class Replica(proto.Message): + r"""Represents a Replica for this + [Secret][google.cloud.secretmanager.v1.Secret]. + + Attributes: + location (str): + The canonical IDs of the location to replicate data. For + example: ``"us-east1"``. + customer_managed_encryption (~.resources.CustomerManagedEncryption): + Optional. The customer-managed encryption configuration of + the [User-Managed Replica][Replication.UserManaged.Replica]. + If no configuration is provided, Google-managed default + encryption is used. + + Updates to the + [Secret][google.cloud.secretmanager.v1.Secret] encryption + configuration only apply to + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + added afterwards. They do not apply retroactively to + existing + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + """ + + location = proto.Field(proto.STRING, number=1) + + customer_managed_encryption = proto.Field( + proto.MESSAGE, number=2, message="CustomerManagedEncryption", + ) + + replicas = proto.RepeatedField( + proto.MESSAGE, number=1, message="Replication.UserManaged.Replica", + ) + + automatic = proto.Field( + proto.MESSAGE, number=1, oneof="replication", message=Automatic, + ) + + user_managed = proto.Field( + proto.MESSAGE, number=2, oneof="replication", message=UserManaged, + ) + + +class CustomerManagedEncryption(proto.Message): + r"""Configuration for encrypting secret payloads using customer- + anaged encryption keys (CMEK). + + Attributes: + kms_key_name (str): + Required. The resource name of the Cloud KMS CryptoKey used + to encrypt secret payloads. + + For secrets using the + [UserManaged][google.cloud.secretmanager.v1.Replication.UserManaged] + replication policy type, Cloud KMS CryptoKeys must reside in + the same location as the [replica + location][Secret.UserManaged.Replica.location]. + + For secrets using the + [Automatic][google.cloud.secretmanager.v1.Replication.Automatic] + replication policy type, Cloud KMS CryptoKeys must reside in + ``global``. + + The expected format is + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + """ + + kms_key_name = proto.Field(proto.STRING, number=1) + + +class ReplicationStatus(proto.Message): + r"""The replication status of a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Attributes: + automatic (~.resources.ReplicationStatus.AutomaticStatus): + Describes the replication status of a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + with automatic replication. + + Only populated if the parent + [Secret][google.cloud.secretmanager.v1.Secret] has an + automatic replication policy. + user_managed (~.resources.ReplicationStatus.UserManagedStatus): + Describes the replication status of a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + with user-managed replication. + + Only populated if the parent + [Secret][google.cloud.secretmanager.v1.Secret] has a + user-managed replication policy. + """ + + class AutomaticStatus(proto.Message): + r"""The replication status of a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] using + automatic replication. + + Only populated if the parent + [Secret][google.cloud.secretmanager.v1.Secret] has an automatic + replication policy. + + Attributes: + customer_managed_encryption (~.resources.CustomerManagedEncryptionStatus): + Output only. The customer-managed encryption status of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + Only populated if customer-managed encryption is used. + """ + + customer_managed_encryption = proto.Field( + proto.MESSAGE, number=1, message="CustomerManagedEncryptionStatus", + ) + + class UserManagedStatus(proto.Message): + r"""The replication status of a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] using + user-managed replication. + + Only populated if the parent + [Secret][google.cloud.secretmanager.v1.Secret] has a user-managed + replication policy. + + Attributes: + replicas (Sequence[~.resources.ReplicationStatus.UserManagedStatus.ReplicaStatus]): + Output only. The list of replica statuses for the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + """ + + class ReplicaStatus(proto.Message): + r"""Describes the status of a user-managed replica for the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Attributes: + location (str): + Output only. The canonical ID of the replica location. For + example: ``"us-east1"``. + customer_managed_encryption (~.resources.CustomerManagedEncryptionStatus): + Output only. The customer-managed encryption status of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + Only populated if customer-managed encryption is used. + """ + + location = proto.Field(proto.STRING, number=1) + + customer_managed_encryption = proto.Field( + proto.MESSAGE, number=2, message="CustomerManagedEncryptionStatus", + ) + + replicas = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ReplicationStatus.UserManagedStatus.ReplicaStatus", + ) + + automatic = proto.Field( + proto.MESSAGE, number=1, oneof="replication_status", message=AutomaticStatus, + ) + + user_managed = proto.Field( + proto.MESSAGE, number=2, oneof="replication_status", message=UserManagedStatus, + ) + + +class CustomerManagedEncryptionStatus(proto.Message): + r"""Describes the status of customer-managed encryption. + + Attributes: + kms_key_version_name (str): + Required. The resource name of the Cloud KMS + CryptoKeyVersion used to encrypt the secret payload, in the + following format: + ``projects/*/locations/*/keyRings/*/cryptoKeys/*/versions/*``. + """ + + kms_key_version_name = proto.Field(proto.STRING, number=1) + + +class SecretPayload(proto.Message): + r"""A secret payload resource in the Secret Manager API. This contains + the sensitive secret payload that is associated with a + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + + Attributes: + data (bytes): + The secret data. Must be no larger than + 64KiB. + """ + + data = proto.Field(proto.BYTES, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/secretmanager_v1/types/service.py b/google/cloud/secretmanager_v1/types/service.py new file mode 100644 index 0000000..406095d --- /dev/null +++ b/google/cloud/secretmanager_v1/types/service.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.secretmanager_v1.types import resources +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.secretmanager.v1", + manifest={ + "ListSecretsRequest", + "ListSecretsResponse", + "CreateSecretRequest", + "AddSecretVersionRequest", + "GetSecretRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "GetSecretVersionRequest", + "UpdateSecretRequest", + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "DeleteSecretRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "DestroySecretVersionRequest", + }, +) + + +class ListSecretsRequest(proto.Message): + r"""Request message for + [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. + + Attributes: + parent (str): + Required. The resource name of the project associated with + the [Secrets][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*``. + page_size (int): + Optional. The maximum number of results to be + returned in a single page. If set to 0, the + server decides the number of results to return. + If the number is greater than 25000, it is + capped at 25000. + page_token (str): + Optional. Pagination token, returned earlier via + [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSecretsResponse(proto.Message): + r"""Response message for + [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. + + Attributes: + secrets (Sequence[~.resources.Secret]): + The list of [Secrets][google.cloud.secretmanager.v1.Secret] + sorted in reverse by create_time (newest first). + next_page_token (str): + A token to retrieve the next page of results. Pass this + value in + [ListSecretsRequest.page_token][google.cloud.secretmanager.v1.ListSecretsRequest.page_token] + to retrieve the next page. + total_size (int): + The total number of + [Secrets][google.cloud.secretmanager.v1.Secret]. + """ + + @property + def raw_page(self): + return self + + secrets = proto.RepeatedField(proto.MESSAGE, number=1, message=resources.Secret,) + + next_page_token = proto.Field(proto.STRING, number=2) + + total_size = proto.Field(proto.INT32, number=3) + + +class CreateSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.CreateSecret][google.cloud.secretmanager.v1.SecretManagerService.CreateSecret]. + + Attributes: + parent (str): + Required. The resource name of the project to associate with + the [Secret][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*``. + secret_id (str): + Required. This must be unique within the project. + + A secret ID is a string with a maximum length of 255 + characters and can contain uppercase and lowercase letters, + numerals, and the hyphen (``-``) and underscore (``_``) + characters. + secret (~.resources.Secret): + Required. A [Secret][google.cloud.secretmanager.v1.Secret] + with initial field values. + """ + + parent = proto.Field(proto.STRING, number=1) + + secret_id = proto.Field(proto.STRING, number=2) + + secret = proto.Field(proto.MESSAGE, number=3, message=resources.Secret,) + + +class AddSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.AddSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AddSecretVersion]. + + Attributes: + parent (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to associate + with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*``. + payload (~.resources.SecretPayload): + Required. The secret payload of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + """ + + parent = proto.Field(proto.STRING, number=1) + + payload = proto.Field(proto.MESSAGE, number=2, message=resources.SecretPayload,) + + +class GetSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.GetSecret][google.cloud.secretmanager.v1.SecretManagerService.GetSecret]. + + Attributes: + name (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret], in the + format ``projects/*/secrets/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListSecretVersionsRequest(proto.Message): + r"""Request message for + [SecretManagerService.ListSecretVersions][google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. + + Attributes: + parent (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] associated + with the + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + to list, in the format ``projects/*/secrets/*``. + page_size (int): + Optional. The maximum number of results to be + returned in a single page. If set to 0, the + server decides the number of results to return. + If the number is greater than 25000, it is + capped at 25000. + page_token (str): + Optional. Pagination token, returned earlier via + ListSecretVersionsResponse.next_page_token][]. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSecretVersionsResponse(proto.Message): + r"""Response message for + [SecretManagerService.ListSecretVersions][google.cloud.secretmanager.v1.SecretManagerService.ListSecretVersions]. + + Attributes: + versions (Sequence[~.resources.SecretVersion]): + The list of + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion] + sorted in reverse by create_time (newest first). + next_page_token (str): + A token to retrieve the next page of results. Pass this + value in + [ListSecretVersionsRequest.page_token][google.cloud.secretmanager.v1.ListSecretVersionsRequest.page_token] + to retrieve the next page. + total_size (int): + The total number of + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, number=1, message=resources.SecretVersion, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + total_size = proto.Field(proto.INT32, number=3) + + +class GetSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.GetSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.GetSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.UpdateSecret][google.cloud.secretmanager.v1.SecretManagerService.UpdateSecret]. + + Attributes: + secret (~.resources.Secret): + Required. [Secret][google.cloud.secretmanager.v1.Secret] + with updated field values. + update_mask (~.field_mask.FieldMask): + Required. Specifies the fields to be updated. + """ + + secret = proto.Field(proto.MESSAGE, number=1, message=resources.Secret,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class AccessSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.AccessSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class AccessSecretVersionResponse(proto.Message): + r"""Response message for + [SecretManagerService.AccessSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion]. + + Attributes: + name (str): + The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + payload (~.resources.SecretPayload): + Secret payload + """ + + name = proto.Field(proto.STRING, number=1) + + payload = proto.Field(proto.MESSAGE, number=2, message=resources.SecretPayload,) + + +class DeleteSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.DeleteSecret][google.cloud.secretmanager.v1.SecretManagerService.DeleteSecret]. + + Attributes: + name (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to delete in + the format ``projects/*/secrets/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DisableSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.DisableSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.DisableSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to disable in the format + ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class EnableSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.EnableSecretVersion][google.cloud.secretmanager.v1.SecretManagerService.EnableSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to enable in the format ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DestroySecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.DestroySecretVersion][google.cloud.secretmanager.v1.SecretManagerService.DestroySecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + to destroy in the format + ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/secretmanager_v1beta1/__init__.py b/google/cloud/secretmanager_v1beta1/__init__.py index 86fd5ac..94ea22d 100644 --- a/google/cloud/secretmanager_v1beta1/__init__.py +++ b/google/cloud/secretmanager_v1beta1/__init__.py @@ -1,47 +1,61 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.secretmanager_v1beta1 import types -from google.cloud.secretmanager_v1beta1.gapic import enums -from google.cloud.secretmanager_v1beta1.gapic import secret_manager_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecretManagerServiceClient( - secret_manager_service_client.SecretManagerServiceClient -): - __doc__ = secret_manager_service_client.SecretManagerServiceClient.__doc__ - enums = enums +from .services.secret_manager_service import SecretManagerServiceClient +from .types.resources import Replication +from .types.resources import Secret +from .types.resources import SecretPayload +from .types.resources import SecretVersion +from .types.service import AccessSecretVersionRequest +from .types.service import AccessSecretVersionResponse +from .types.service import AddSecretVersionRequest +from .types.service import CreateSecretRequest +from .types.service import DeleteSecretRequest +from .types.service import DestroySecretVersionRequest +from .types.service import DisableSecretVersionRequest +from .types.service import EnableSecretVersionRequest +from .types.service import GetSecretRequest +from .types.service import GetSecretVersionRequest +from .types.service import ListSecretVersionsRequest +from .types.service import ListSecretVersionsResponse +from .types.service import ListSecretsRequest +from .types.service import ListSecretsResponse +from .types.service import UpdateSecretRequest __all__ = ( - "enums", - "types", + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "AddSecretVersionRequest", + "CreateSecretRequest", + "DeleteSecretRequest", + "DestroySecretVersionRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "GetSecretRequest", + "GetSecretVersionRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "ListSecretsRequest", + "ListSecretsResponse", + "Replication", + "Secret", + "SecretPayload", + "SecretVersion", + "UpdateSecretRequest", "SecretManagerServiceClient", ) diff --git a/google/cloud/secretmanager_v1beta1/gapic/__init__.py b/google/cloud/secretmanager_v1beta1/gapic/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/secretmanager_v1beta1/gapic/enums.py b/google/cloud/secretmanager_v1beta1/gapic/enums.py deleted file mode 100644 index e77df68..0000000 --- a/google/cloud/secretmanager_v1beta1/gapic/enums.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class SecretVersion(object): - class State(enum.IntEnum): - """ - The state of a ``SecretVersion``, indicating if it can be accessed. - - Attributes: - STATE_UNSPECIFIED (int): Not specified. This value is unused and invalid. - ENABLED (int): The ``SecretVersion`` may be accessed. - DISABLED (int): The ``SecretVersion`` may not be accessed, but the secret data is - still available and can be placed back into the ``ENABLED`` state. - DESTROYED (int): The ``SecretVersion`` is destroyed and the secret data is no longer - stored. A version may not leave this state once entered. - """ - - STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - DESTROYED = 3 diff --git a/google/cloud/secretmanager_v1beta1/gapic/secret_manager_service_client.py b/google/cloud/secretmanager_v1beta1/gapic/secret_manager_service_client.py deleted file mode 100644 index 3bb23c6..0000000 --- a/google/cloud/secretmanager_v1beta1/gapic/secret_manager_service_client.py +++ /dev/null @@ -1,1441 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.secrets.v1beta1 SecretManagerService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.secretmanager_v1beta1.gapic import enums -from google.cloud.secretmanager_v1beta1.gapic import ( - secret_manager_service_client_config, -) -from google.cloud.secretmanager_v1beta1.gapic.transports import ( - secret_manager_service_grpc_transport, -) -from google.cloud.secretmanager_v1beta1.proto import resources_pb2 -from google.cloud.secretmanager_v1beta1.proto import service_pb2 -from google.cloud.secretmanager_v1beta1.proto import service_pb2_grpc -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-secret-manager", -).version - - -class SecretManagerServiceClient(object): - """ - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - - ``Secret`` - - ``SecretVersion`` - """ - - SERVICE_ADDRESS = "secretmanager.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.secrets.v1beta1.SecretManagerService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SecretManagerServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def project_path(cls, project): - """Return a fully-qualified project string.""" - return google.api_core.path_template.expand( - "projects/{project}", project=project, - ) - - @classmethod - def secret_path(cls, project, secret): - """Return a fully-qualified secret string.""" - return google.api_core.path_template.expand( - "projects/{project}/secrets/{secret}", project=project, secret=secret, - ) - - @classmethod - def secret_version_path(cls, project, secret, secret_version): - """Return a fully-qualified secret_version string.""" - return google.api_core.path_template.expand( - "projects/{project}/secrets/{secret}/versions/{secret_version}", - project=project, - secret=secret, - secret_version=secret_version, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.SecretManagerServiceGrpcTransport, - Callable[[~.Credentials, type], ~.SecretManagerServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = secret_manager_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=secret_manager_service_grpc_transport.SecretManagerServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = secret_manager_service_grpc_transport.SecretManagerServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_secrets( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ``Secrets``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> parent = client.project_path('[PROJECT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_secrets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_secrets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The resource name of the project associated with the - ``Secrets``, in the format ``projects/*``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.secretmanager_v1beta1.types.Secret` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_secrets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_secrets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_secrets, - default_retry=self._method_configs["ListSecrets"].retry, - default_timeout=self._method_configs["ListSecrets"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListSecretsRequest(parent=parent, page_size=page_size,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_secrets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="secrets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def create_secret( - self, - parent, - secret_id, - secret, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a new ``Secret`` containing no ``SecretVersions``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> parent = client.project_path('[PROJECT]') - >>> - >>> # TODO: Initialize `secret_id`: - >>> secret_id = '' - >>> - >>> # TODO: Initialize `secret`: - >>> secret = {} - >>> - >>> response = client.create_secret(parent, secret_id, secret) - - Args: - parent (str): Required. The resource name of the project to associate with the - ``Secret``, in the format ``projects/*``. - secret_id (str): Required. This must be unique within the project. - - A secret ID is a string with a maximum length of 255 characters and can - contain uppercase and lowercase letters, numerals, and the hyphen - (``-``) and underscore (``_``) characters. - secret (Union[dict, ~google.cloud.secretmanager_v1beta1.types.Secret]): Required. A ``Secret`` with initial field values. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1beta1.types.Secret` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.Secret` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "create_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_secret, - default_retry=self._method_configs["CreateSecret"].retry, - default_timeout=self._method_configs["CreateSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.CreateSecretRequest( - parent=parent, secret_id=secret_id, secret=secret, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def add_secret_version( - self, - parent, - payload, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a new ``SecretVersion`` containing secret data and attaches - it to an existing ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> parent = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> # TODO: Initialize `payload`: - >>> payload = {} - >>> - >>> response = client.add_secret_version(parent, payload) - - Args: - parent (str): Required. The resource name of the ``Secret`` to associate with the - ``SecretVersion`` in the format ``projects/*/secrets/*``. - payload (Union[dict, ~google.cloud.secretmanager_v1beta1.types.SecretPayload]): Required. The secret payload of the ``SecretVersion``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1beta1.types.SecretPayload` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "add_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "add_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.add_secret_version, - default_retry=self._method_configs["AddSecretVersion"].retry, - default_timeout=self._method_configs["AddSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.AddSecretVersionRequest(parent=parent, payload=payload,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["add_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_secret( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets metadata for a given ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> response = client.get_secret(name) - - Args: - name (str): Required. The resource name of the ``Secret``, in the format - ``projects/*/secrets/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.Secret` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "get_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_secret, - default_retry=self._method_configs["GetSecret"].retry, - default_timeout=self._method_configs["GetSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetSecretRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_secret( - self, - secret, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates metadata of an existing ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `secret`: - >>> secret = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_secret(secret, update_mask) - - Args: - secret (Union[dict, ~google.cloud.secretmanager_v1beta1.types.Secret]): Required. ``Secret`` with updated field values. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1beta1.types.Secret` - update_mask (Union[dict, ~google.cloud.secretmanager_v1beta1.types.FieldMask]): Required. Specifies the fields to be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.Secret` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "update_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_secret, - default_retry=self._method_configs["UpdateSecret"].retry, - default_timeout=self._method_configs["UpdateSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.UpdateSecretRequest( - secret=secret, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("secret.name", secret.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_secret( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> client.delete_secret(name) - - Args: - name (str): Required. The resource name of the ``Secret`` to delete in the - format ``projects/*/secrets/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_secret" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_secret" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_secret, - default_retry=self._method_configs["DeleteSecret"].retry, - default_timeout=self._method_configs["DeleteSecret"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DeleteSecretRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_secret"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_secret_versions( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ``SecretVersions``. This call does not return secret data. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> parent = client.secret_path('[PROJECT]', '[SECRET]') - >>> - >>> # Iterate over all results - >>> for element in client.list_secret_versions(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_secret_versions(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The resource name of the ``Secret`` associated with the - ``SecretVersions`` to list, in the format ``projects/*/secrets/*``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.secretmanager_v1beta1.types.SecretVersion` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_secret_versions" not in self._inner_api_calls: - self._inner_api_calls[ - "list_secret_versions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_secret_versions, - default_retry=self._method_configs["ListSecretVersions"].retry, - default_timeout=self._method_configs["ListSecretVersions"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.ListSecretVersionsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_secret_versions"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="versions", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets metadata for a ``SecretVersion``. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.get_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` in the format - ``projects/*/secrets/*/versions/*``. - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "get_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_secret_version, - default_retry=self._method_configs["GetSecretVersion"].retry, - default_timeout=self._method_configs["GetSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.GetSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def access_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Accesses a ``SecretVersion``. This call returns the secret data. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.access_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` in the format - ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.AccessSecretVersionResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "access_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "access_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.access_secret_version, - default_retry=self._method_configs["AccessSecretVersion"].retry, - default_timeout=self._method_configs["AccessSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.AccessSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["access_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def disable_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Disables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DISABLED``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.disable_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` to disable in - the format ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "disable_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "disable_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.disable_secret_version, - default_retry=self._method_configs["DisableSecretVersion"].retry, - default_timeout=self._method_configs["DisableSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DisableSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["disable_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def enable_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Enables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``ENABLED``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.enable_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` to enable in - the format ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "enable_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "enable_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.enable_secret_version, - default_retry=self._method_configs["EnableSecretVersion"].retry, - default_timeout=self._method_configs["EnableSecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.EnableSecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["enable_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def destroy_secret_version( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Destroys a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DESTROYED`` and - irrevocably destroys the secret data. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> name = client.secret_version_path('[PROJECT]', '[SECRET]', '[SECRET_VERSION]') - >>> - >>> response = client.destroy_secret_version(name) - - Args: - name (str): Required. The resource name of the ``SecretVersion`` to destroy in - the format ``projects/*/secrets/*/versions/*``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.SecretVersion` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "destroy_secret_version" not in self._inner_api_calls: - self._inner_api_calls[ - "destroy_secret_version" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.destroy_secret_version, - default_retry=self._method_configs["DestroySecretVersion"].retry, - default_timeout=self._method_configs["DestroySecretVersion"].timeout, - client_info=self._client_info, - ) - - request = service_pb2.DestroySecretVersionRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["destroy_secret_version"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def set_iam_policy( - self, - resource, - policy, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sets the access control policy on the specified secret. Replaces any - existing policy. - - Permissions on ``SecretVersions`` are enforced according to the policy - set on the associated ``Secret``. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `policy`: - >>> policy = {} - >>> - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (str): REQUIRED: The resource for which the policy is being specified. - See the operation documentation for the appropriate value for this field. - policy (Union[dict, ~google.cloud.secretmanager_v1beta1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The - size of the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1beta1.types.Policy` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "set_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_iam_policy, - default_retry=self._method_configs["SetIamPolicy"].retry, - default_timeout=self._method_configs["SetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_iam_policy( - self, - resource, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the access control policy for a secret. - Returns empty policy if the secret exists and does not have a policy set. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> response = client.get_iam_policy(resource) - - Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.secretmanager_v1beta1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.secretmanager_v1beta1.types.GetPolicyOptions` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "get_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns permissions that a caller has for the specified secret. If - the secret does not exist, this call returns an empty set of - permissions, not a NOT_FOUND error. - - Note: This operation is designed to be used for building - permission-aware UIs and command-line tools, not for authorization - checking. This operation may "fail open" without warning. - - Example: - >>> from google.cloud import secretmanager_v1beta1 - >>> - >>> client = secretmanager_v1beta1.SecretManagerServiceClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[str]): The set of permissions to check for the ``resource``. Permissions - with wildcards (such as '*' or 'storage.*') are not allowed. For more - information see `IAM - Overview `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.secretmanager_v1beta1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/secretmanager_v1beta1/gapic/secret_manager_service_client_config.py b/google/cloud/secretmanager_v1beta1/gapic/secret_manager_service_client_config.py deleted file mode 100644 index 9cb96e9..0000000 --- a/google/cloud/secretmanager_v1beta1/gapic/secret_manager_service_client_config.py +++ /dev/null @@ -1,117 +0,0 @@ -config = { - "interfaces": { - "google.cloud.secrets.v1beta1.SecretManagerService": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "UNKNOWN"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 1000, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ListSecrets": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "AddSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DeleteSecret": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "ListSecretVersions": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "AccessSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "DisableSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "EnableSecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DestroySecretVersion": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - }, - } - } -} diff --git a/google/cloud/secretmanager_v1beta1/gapic/transports/__init__.py b/google/cloud/secretmanager_v1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/secretmanager_v1beta1/gapic/transports/secret_manager_service_grpc_transport.py b/google/cloud/secretmanager_v1beta1/gapic/transports/secret_manager_service_grpc_transport.py deleted file mode 100644 index 5c55caa..0000000 --- a/google/cloud/secretmanager_v1beta1/gapic/transports/secret_manager_service_grpc_transport.py +++ /dev/null @@ -1,330 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.secretmanager_v1beta1.proto import service_pb2_grpc - - -class SecretManagerServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.secrets.v1beta1 SecretManagerService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="secretmanager.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "secret_manager_service_stub": service_pb2_grpc.SecretManagerServiceStub( - channel - ), - } - - @classmethod - def create_channel( - cls, address="secretmanager.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_secrets(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.list_secrets`. - - Lists ``Secrets``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].ListSecrets - - @property - def create_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.create_secret`. - - Creates a new ``Secret`` containing no ``SecretVersions``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].CreateSecret - - @property - def add_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.add_secret_version`. - - Creates a new ``SecretVersion`` containing secret data and attaches - it to an existing ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].AddSecretVersion - - @property - def get_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.get_secret`. - - Gets metadata for a given ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].GetSecret - - @property - def update_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.update_secret`. - - Updates metadata of an existing ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].UpdateSecret - - @property - def delete_secret(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.delete_secret`. - - Deletes a ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].DeleteSecret - - @property - def list_secret_versions(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.list_secret_versions`. - - Lists ``SecretVersions``. This call does not return secret data. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].ListSecretVersions - - @property - def get_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.get_secret_version`. - - Gets metadata for a ``SecretVersion``. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].GetSecretVersion - - @property - def access_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.access_secret_version`. - - Accesses a ``SecretVersion``. This call returns the secret data. - - ``projects/*/secrets/*/versions/latest`` is an alias to the ``latest`` - ``SecretVersion``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].AccessSecretVersion - - @property - def disable_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.disable_secret_version`. - - Disables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DISABLED``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].DisableSecretVersion - - @property - def enable_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.enable_secret_version`. - - Enables a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``ENABLED``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].EnableSecretVersion - - @property - def destroy_secret_version(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.destroy_secret_version`. - - Destroys a ``SecretVersion``. - - Sets the ``state`` of the ``SecretVersion`` to ``DESTROYED`` and - irrevocably destroys the secret data. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].DestroySecretVersion - - @property - def set_iam_policy(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.set_iam_policy`. - - Sets the access control policy on the specified secret. Replaces any - existing policy. - - Permissions on ``SecretVersions`` are enforced according to the policy - set on the associated ``Secret``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].SetIamPolicy - - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.get_iam_policy`. - - Gets the access control policy for a secret. - Returns empty policy if the secret exists and does not have a policy set. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].GetIamPolicy - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecretManagerServiceClient.test_iam_permissions`. - - Returns permissions that a caller has for the specified secret. If - the secret does not exist, this call returns an empty set of - permissions, not a NOT_FOUND error. - - Note: This operation is designed to be used for building - permission-aware UIs and command-line tools, not for authorization - checking. This operation may "fail open" without warning. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["secret_manager_service_stub"].TestIamPermissions diff --git a/google/cloud/secretmanager_v1beta1/proto/__init__.py b/google/cloud/secretmanager_v1beta1/proto/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/secretmanager_v1beta1/proto/resources_pb2.py b/google/cloud/secretmanager_v1beta1/proto/resources_pb2.py deleted file mode 100644 index 1601d86..0000000 --- a/google/cloud/secretmanager_v1beta1/proto/resources_pb2.py +++ /dev/null @@ -1,799 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/secrets_v1beta1/proto/resources.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/secrets_v1beta1/proto/resources.proto", - package="google.cloud.secrets.v1beta1", - syntax="proto3", - serialized_options=b'\n&com.google.cloud.secretmanager.v1beta1B\016ResourcesProtoP\001ZOgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1;secretmanager\370\001\001\242\002\003GSM\252\002"Google.Cloud.SecretManager.V1Beta1\312\002"Google\\Cloud\\SecretManager\\V1beta1\352\002%Google::Cloud::SecretManager::V1beta1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n2google/cloud/secrets_v1beta1/proto/resources.proto\x12\x1cgoogle.cloud.secrets.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto"\xd9\x02\n\x06Secret\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x03\x12\x46\n\x0breplication\x18\x02 \x01(\x0b\x32).google.cloud.secrets.v1beta1.ReplicationB\x06\xe0\x41\x05\xe0\x41\x02\x12\x34\n\x0b\x63reate_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12@\n\x06labels\x18\x04 \x03(\x0b\x32\x30.google.cloud.secrets.v1beta1.Secret.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01:M\xea\x41J\n#secretmanager.googleapis.com/Secret\x12#projects/{project}/secrets/{secret}"\x90\x03\n\rSecretVersion\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x03\x12\x34\n\x0b\x63reate_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x35\n\x0c\x64\x65stroy_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12\x45\n\x05state\x18\x04 \x01(\x0e\x32\x31.google.cloud.secrets.v1beta1.SecretVersion.StateB\x03\xe0\x41\x03"H\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x45NABLED\x10\x01\x12\x0c\n\x08\x44ISABLED\x10\x02\x12\r\n\tDESTROYED\x10\x03:n\xea\x41k\n*secretmanager.googleapis.com/SecretVersion\x12=projects/{project}/secrets/{secret}/versions/{secret_version}"\xc5\x02\n\x0bReplication\x12H\n\tautomatic\x18\x01 \x01(\x0b\x32\x33.google.cloud.secrets.v1beta1.Replication.AutomaticH\x00\x12M\n\x0cuser_managed\x18\x02 \x01(\x0b\x32\x35.google.cloud.secrets.v1beta1.Replication.UserManagedH\x00\x1a\x0b\n\tAutomatic\x1a\x80\x01\n\x0bUserManaged\x12T\n\x08replicas\x18\x01 \x03(\x0b\x32=.google.cloud.secrets.v1beta1.Replication.UserManaged.ReplicaB\x03\xe0\x41\x02\x1a\x1b\n\x07Replica\x12\x10\n\x08location\x18\x01 \x01(\tB\r\n\x0breplication"\x1d\n\rSecretPayload\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x42\x86\x02\n&com.google.cloud.secretmanager.v1beta1B\x0eResourcesProtoP\x01ZOgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1;secretmanager\xf8\x01\x01\xa2\x02\x03GSM\xaa\x02"Google.Cloud.SecretManager.V1Beta1\xca\x02"Google\\Cloud\\SecretManager\\V1beta1\xea\x02%Google::Cloud::SecretManager::V1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_SECRETVERSION_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.secrets.v1beta1.SecretVersion.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ENABLED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DISABLED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DESTROYED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=772, - serialized_end=844, -) -_sym_db.RegisterEnumDescriptor(_SECRETVERSION_STATE) - - -_SECRET_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.secrets.v1beta1.Secret.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.secrets.v1beta1.Secret.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.secrets.v1beta1.Secret.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=429, - serialized_end=474, -) - -_SECRET = _descriptor.Descriptor( - name="Secret", - full_name="google.cloud.secrets.v1beta1.Secret", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.Secret.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="replication", - full_name="google.cloud.secrets.v1beta1.Secret.replication", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\005\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.secrets.v1beta1.Secret.create_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.secrets.v1beta1.Secret.labels", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SECRET_LABELSENTRY,], - enum_types=[], - serialized_options=b"\352AJ\n#secretmanager.googleapis.com/Secret\022#projects/{project}/secrets/{secret}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=208, - serialized_end=553, -) - - -_SECRETVERSION = _descriptor.Descriptor( - name="SecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretVersion", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.SecretVersion.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.secrets.v1beta1.SecretVersion.create_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="destroy_time", - full_name="google.cloud.secrets.v1beta1.SecretVersion.destroy_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.secrets.v1beta1.SecretVersion.state", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_SECRETVERSION_STATE,], - serialized_options=b"\352Ak\n*secretmanager.googleapis.com/SecretVersion\022=projects/{project}/secrets/{secret}/versions/{secret_version}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=556, - serialized_end=956, -) - - -_REPLICATION_AUTOMATIC = _descriptor.Descriptor( - name="Automatic", - full_name="google.cloud.secrets.v1beta1.Replication.Automatic", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1127, - serialized_end=1138, -) - -_REPLICATION_USERMANAGED_REPLICA = _descriptor.Descriptor( - name="Replica", - full_name="google.cloud.secrets.v1beta1.Replication.UserManaged.Replica", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="location", - full_name="google.cloud.secrets.v1beta1.Replication.UserManaged.Replica.location", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1242, - serialized_end=1269, -) - -_REPLICATION_USERMANAGED = _descriptor.Descriptor( - name="UserManaged", - full_name="google.cloud.secrets.v1beta1.Replication.UserManaged", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="replicas", - full_name="google.cloud.secrets.v1beta1.Replication.UserManaged.replicas", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_REPLICATION_USERMANAGED_REPLICA,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1141, - serialized_end=1269, -) - -_REPLICATION = _descriptor.Descriptor( - name="Replication", - full_name="google.cloud.secrets.v1beta1.Replication", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="automatic", - full_name="google.cloud.secrets.v1beta1.Replication.automatic", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="user_managed", - full_name="google.cloud.secrets.v1beta1.Replication.user_managed", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_REPLICATION_AUTOMATIC, _REPLICATION_USERMANAGED,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="replication", - full_name="google.cloud.secrets.v1beta1.Replication.replication", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=959, - serialized_end=1284, -) - - -_SECRETPAYLOAD = _descriptor.Descriptor( - name="SecretPayload", - full_name="google.cloud.secrets.v1beta1.SecretPayload", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.secrets.v1beta1.SecretPayload.data", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1286, - serialized_end=1315, -) - -_SECRET_LABELSENTRY.containing_type = _SECRET -_SECRET.fields_by_name["replication"].message_type = _REPLICATION -_SECRET.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SECRET.fields_by_name["labels"].message_type = _SECRET_LABELSENTRY -_SECRETVERSION.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SECRETVERSION.fields_by_name[ - "destroy_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SECRETVERSION.fields_by_name["state"].enum_type = _SECRETVERSION_STATE -_SECRETVERSION_STATE.containing_type = _SECRETVERSION -_REPLICATION_AUTOMATIC.containing_type = _REPLICATION -_REPLICATION_USERMANAGED_REPLICA.containing_type = _REPLICATION_USERMANAGED -_REPLICATION_USERMANAGED.fields_by_name[ - "replicas" -].message_type = _REPLICATION_USERMANAGED_REPLICA -_REPLICATION_USERMANAGED.containing_type = _REPLICATION -_REPLICATION.fields_by_name["automatic"].message_type = _REPLICATION_AUTOMATIC -_REPLICATION.fields_by_name["user_managed"].message_type = _REPLICATION_USERMANAGED -_REPLICATION.oneofs_by_name["replication"].fields.append( - _REPLICATION.fields_by_name["automatic"] -) -_REPLICATION.fields_by_name["automatic"].containing_oneof = _REPLICATION.oneofs_by_name[ - "replication" -] -_REPLICATION.oneofs_by_name["replication"].fields.append( - _REPLICATION.fields_by_name["user_managed"] -) -_REPLICATION.fields_by_name[ - "user_managed" -].containing_oneof = _REPLICATION.oneofs_by_name["replication"] -DESCRIPTOR.message_types_by_name["Secret"] = _SECRET -DESCRIPTOR.message_types_by_name["SecretVersion"] = _SECRETVERSION -DESCRIPTOR.message_types_by_name["Replication"] = _REPLICATION -DESCRIPTOR.message_types_by_name["SecretPayload"] = _SECRETPAYLOAD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Secret = _reflection.GeneratedProtocolMessageType( - "Secret", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _SECRET_LABELSENTRY, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.Secret.LabelsEntry) - }, - ), - "DESCRIPTOR": _SECRET, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """A [Secret][google.cloud.secrets.v1beta1.Secret] is a logical secret - whose value and versions can be accessed. A - [Secret][google.cloud.secrets.v1beta1.Secret] is made up of zero or - more [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] that - represent the secret data. - - Attributes: - name: - Output only. The resource name of the - [Secret][google.cloud.secrets.v1beta1.Secret] in the format - ``projects/*/secrets/*``. - replication: - Required. Immutable. The replication policy of the secret data - attached to the [Secret][google.cloud.secrets.v1beta1.Secret]. - The replication policy cannot be changed after the Secret has - been created. - create_time: - Output only. The time at which the - [Secret][google.cloud.secrets.v1beta1.Secret] was created. - labels: - The labels assigned to this Secret. Label keys must be - between 1 and 63 characters long, have a UTF-8 encoding of - maximum 128 bytes, and must conform to the following PCRE - regular expression: - ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}`` Label values - must be between 0 and 63 characters long, have a UTF-8 - encoding of maximum 128 bytes, and must conform to the - following PCRE regular expression: - ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}`` No more than 64 labels can be - assigned to a given resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.Secret) - }, -) -_sym_db.RegisterMessage(Secret) -_sym_db.RegisterMessage(Secret.LabelsEntry) - -SecretVersion = _reflection.GeneratedProtocolMessageType( - "SecretVersion", - (_message.Message,), - { - "DESCRIPTOR": _SECRETVERSION, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """A secret version resource in the Secret Manager API. - - Attributes: - name: - Output only. The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in - the format ``projects/*/secrets/*/versions/*``. - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] - IDs in a [Secret][google.cloud.secrets.v1beta1.Secret] start - at 1 and are incremented for each subsequent version of the - secret. - create_time: - Output only. The time at which the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] - was created. - destroy_time: - Output only. The time this - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] - was destroyed. Only present if - [state][google.cloud.secrets.v1beta1.SecretVersion.state] is [ - DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DE - STROYED]. - state: - Output only. The current state of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.SecretVersion) - }, -) -_sym_db.RegisterMessage(SecretVersion) - -Replication = _reflection.GeneratedProtocolMessageType( - "Replication", - (_message.Message,), - { - "Automatic": _reflection.GeneratedProtocolMessageType( - "Automatic", - (_message.Message,), - { - "DESCRIPTOR": _REPLICATION_AUTOMATIC, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """A replication policy that replicates the - [Secret][google.cloud.secrets.v1beta1.Secret] payload without any - restrictions.""", - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.Replication.Automatic) - }, - ), - "UserManaged": _reflection.GeneratedProtocolMessageType( - "UserManaged", - (_message.Message,), - { - "Replica": _reflection.GeneratedProtocolMessageType( - "Replica", - (_message.Message,), - { - "DESCRIPTOR": _REPLICATION_USERMANAGED_REPLICA, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """Represents a Replica for this - [Secret][google.cloud.secrets.v1beta1.Secret]. - - Attributes: - location: - The canonical IDs of the location to replicate data. For - example: ``"us-east1"``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.Replication.UserManaged.Replica) - }, - ), - "DESCRIPTOR": _REPLICATION_USERMANAGED, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """A replication policy that replicates the - [Secret][google.cloud.secrets.v1beta1.Secret] payload into the - locations specified in [Secret.replication.user_managed.replicas][] - - Attributes: - replicas: - Required. The list of Replicas for this - [Secret][google.cloud.secrets.v1beta1.Secret]. Cannot be - empty. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.Replication.UserManaged) - }, - ), - "DESCRIPTOR": _REPLICATION, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """A policy that defines the replication configuration of data. - - Attributes: - replication: - The replication policy for this secret. - automatic: - The [Secret][google.cloud.secrets.v1beta1.Secret] will - automatically be replicated without any restrictions. - user_managed: - The [Secret][google.cloud.secrets.v1beta1.Secret] will only be - replicated into the locations specified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.Replication) - }, -) -_sym_db.RegisterMessage(Replication) -_sym_db.RegisterMessage(Replication.Automatic) -_sym_db.RegisterMessage(Replication.UserManaged) -_sym_db.RegisterMessage(Replication.UserManaged.Replica) - -SecretPayload = _reflection.GeneratedProtocolMessageType( - "SecretPayload", - (_message.Message,), - { - "DESCRIPTOR": _SECRETPAYLOAD, - "__module__": "google.cloud.secrets_v1beta1.proto.resources_pb2", - "__doc__": """A secret payload resource in the Secret Manager API. This contains the - sensitive secret data that is associated with a - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Attributes: - data: - The secret data. Must be no larger than 64KiB. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.SecretPayload) - }, -) -_sym_db.RegisterMessage(SecretPayload) - - -DESCRIPTOR._options = None -_SECRET_LABELSENTRY._options = None -_SECRET.fields_by_name["name"]._options = None -_SECRET.fields_by_name["replication"]._options = None -_SECRET.fields_by_name["create_time"]._options = None -_SECRET._options = None -_SECRETVERSION.fields_by_name["name"]._options = None -_SECRETVERSION.fields_by_name["create_time"]._options = None -_SECRETVERSION.fields_by_name["destroy_time"]._options = None -_SECRETVERSION.fields_by_name["state"]._options = None -_SECRETVERSION._options = None -_REPLICATION_USERMANAGED.fields_by_name["replicas"]._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/secretmanager_v1beta1/proto/resources_pb2_grpc.py b/google/cloud/secretmanager_v1beta1/proto/resources_pb2_grpc.py deleted file mode 100644 index 8a93939..0000000 --- a/google/cloud/secretmanager_v1beta1/proto/resources_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/secretmanager_v1beta1/proto/service_pb2.py b/google/cloud/secretmanager_v1beta1/proto/service_pb2.py deleted file mode 100644 index a5d027d..0000000 --- a/google/cloud/secretmanager_v1beta1/proto/service_pb2.py +++ /dev/null @@ -1,1531 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/secrets_v1beta1/proto/service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.secretmanager_v1beta1.proto import ( - resources_pb2 as google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/secrets_v1beta1/proto/service.proto", - package="google.cloud.secrets.v1beta1", - syntax="proto3", - serialized_options=b'\n&com.google.cloud.secretmanager.v1beta1B\014ServiceProtoP\001ZOgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1;secretmanager\370\001\001\242\002\003GSM\252\002"Google.Cloud.SecretManager.V1Beta1\312\002"Google\\Cloud\\SecretManager\\V1beta1\352\002%Google::Cloud::SecretManager::V1beta1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n0google/cloud/secrets_v1beta1/proto/service.proto\x12\x1cgoogle.cloud.secrets.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x32google/cloud/secrets_v1beta1/proto/resources.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto"\x8a\x01\n\x12ListSecretsRequest\x12\x43\n\x06parent\x18\x01 \x01(\tB3\xe0\x41\x02\xfa\x41-\n+cloudresourcemanager.googleapis.com/Project\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01"y\n\x13ListSecretsResponse\x12\x35\n\x07secrets\x18\x01 \x03(\x0b\x32$.google.cloud.secrets.v1beta1.Secret\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\x12\x12\n\ntotal_size\x18\x03 \x01(\x05"\xad\x01\n\x13\x43reateSecretRequest\x12\x43\n\x06parent\x18\x01 \x01(\tB3\xe0\x41\x02\xfa\x41-\n+cloudresourcemanager.googleapis.com/Project\x12\x16\n\tsecret_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x39\n\x06secret\x18\x03 \x01(\x0b\x32$.google.cloud.secrets.v1beta1.SecretB\x03\xe0\x41\x02"\x99\x01\n\x17\x41\x64\x64SecretVersionRequest\x12;\n\x06parent\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret\x12\x41\n\x07payload\x18\x02 \x01(\x0b\x32+.google.cloud.secrets.v1beta1.SecretPayloadB\x03\xe0\x41\x02"M\n\x10GetSecretRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret"\x89\x01\n\x19ListSecretVersionsRequest\x12;\n\x06parent\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01"\x88\x01\n\x1aListSecretVersionsResponse\x12=\n\x08versions\x18\x01 \x03(\x0b\x32+.google.cloud.secrets.v1beta1.SecretVersion\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\x12\x12\n\ntotal_size\x18\x03 \x01(\x05"[\n\x17GetSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"\x86\x01\n\x13UpdateSecretRequest\x12\x39\n\x06secret\x18\x01 \x01(\x0b\x32$.google.cloud.secrets.v1beta1.SecretB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"^\n\x1a\x41\x63\x63\x65ssSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"\x9a\x01\n\x1b\x41\x63\x63\x65ssSecretVersionResponse\x12=\n\x04name\x18\x01 \x01(\tB/\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion\x12<\n\x07payload\x18\x02 \x01(\x0b\x32+.google.cloud.secrets.v1beta1.SecretPayload"P\n\x13\x44\x65leteSecretRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#secretmanager.googleapis.com/Secret"_\n\x1b\x44isableSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"^\n\x1a\x45nableSecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion"_\n\x1b\x44\x65stroySecretVersionRequest\x12@\n\x04name\x18\x01 \x01(\tB2\xe0\x41\x02\xfa\x41,\n*secretmanager.googleapis.com/SecretVersion2\x83\x16\n\x14SecretManagerService\x12\xa9\x01\n\x0bListSecrets\x12\x30.google.cloud.secrets.v1beta1.ListSecretsRequest\x1a\x31.google.cloud.secrets.v1beta1.ListSecretsResponse"5\x82\xd3\xe4\x93\x02&\x12$/v1beta1/{parent=projects/*}/secrets\xda\x41\x06parent\x12\xb7\x01\n\x0c\x43reateSecret\x12\x31.google.cloud.secrets.v1beta1.CreateSecretRequest\x1a$.google.cloud.secrets.v1beta1.Secret"N\x82\xd3\xe4\x93\x02."$/v1beta1/{parent=projects/*}/secrets:\x06secret\xda\x41\x17parent,secret_id,secret\x12\xc5\x01\n\x10\x41\x64\x64SecretVersion\x12\x35.google.cloud.secrets.v1beta1.AddSecretVersionRequest\x1a+.google.cloud.secrets.v1beta1.SecretVersion"M\x82\xd3\xe4\x93\x02\x36"1/v1beta1/{parent=projects/*/secrets/*}:addVersion:\x01*\xda\x41\x0eparent,payload\x12\x96\x01\n\tGetSecret\x12..google.cloud.secrets.v1beta1.GetSecretRequest\x1a$.google.cloud.secrets.v1beta1.Secret"3\x82\xd3\xe4\x93\x02&\x12$/v1beta1/{name=projects/*/secrets/*}\xda\x41\x04name\x12\xb9\x01\n\x0cUpdateSecret\x12\x31.google.cloud.secrets.v1beta1.UpdateSecretRequest\x1a$.google.cloud.secrets.v1beta1.Secret"P\x82\xd3\xe4\x93\x02\x35\x32+/v1beta1/{secret.name=projects/*/secrets/*}:\x06secret\xda\x41\x12secret,update_mask\x12\x8e\x01\n\x0c\x44\x65leteSecret\x12\x31.google.cloud.secrets.v1beta1.DeleteSecretRequest\x1a\x16.google.protobuf.Empty"3\x82\xd3\xe4\x93\x02&*$/v1beta1/{name=projects/*/secrets/*}\xda\x41\x04name\x12\xc9\x01\n\x12ListSecretVersions\x12\x37.google.cloud.secrets.v1beta1.ListSecretVersionsRequest\x1a\x38.google.cloud.secrets.v1beta1.ListSecretVersionsResponse"@\x82\xd3\xe4\x93\x02\x31\x12//v1beta1/{parent=projects/*/secrets/*}/versions\xda\x41\x06parent\x12\xb6\x01\n\x10GetSecretVersion\x12\x35.google.cloud.secrets.v1beta1.GetSecretVersionRequest\x1a+.google.cloud.secrets.v1beta1.SecretVersion">\x82\xd3\xe4\x93\x02\x31\x12//v1beta1/{name=projects/*/secrets/*/versions/*}\xda\x41\x04name\x12\xd1\x01\n\x13\x41\x63\x63\x65ssSecretVersion\x12\x38.google.cloud.secrets.v1beta1.AccessSecretVersionRequest\x1a\x39.google.cloud.secrets.v1beta1.AccessSecretVersionResponse"E\x82\xd3\xe4\x93\x02\x38\x12\x36/v1beta1/{name=projects/*/secrets/*/versions/*}:access\xda\x41\x04name\x12\xc9\x01\n\x14\x44isableSecretVersion\x12\x39.google.cloud.secrets.v1beta1.DisableSecretVersionRequest\x1a+.google.cloud.secrets.v1beta1.SecretVersion"I\x82\xd3\xe4\x93\x02<"7/v1beta1/{name=projects/*/secrets/*/versions/*}:disable:\x01*\xda\x41\x04name\x12\xc6\x01\n\x13\x45nableSecretVersion\x12\x38.google.cloud.secrets.v1beta1.EnableSecretVersionRequest\x1a+.google.cloud.secrets.v1beta1.SecretVersion"H\x82\xd3\xe4\x93\x02;"6/v1beta1/{name=projects/*/secrets/*/versions/*}:enable:\x01*\xda\x41\x04name\x12\xc9\x01\n\x14\x44\x65stroySecretVersion\x12\x39.google.cloud.secrets.v1beta1.DestroySecretVersionRequest\x1a+.google.cloud.secrets.v1beta1.SecretVersion"I\x82\xd3\xe4\x93\x02<"7/v1beta1/{name=projects/*/secrets/*/versions/*}:destroy:\x01*\xda\x41\x04name\x12\x8b\x01\n\x0cSetIamPolicy\x12".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"@\x82\xd3\xe4\x93\x02:"5/v1beta1/{resource=projects/*/secrets/*}:setIamPolicy:\x01*\x12\x88\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"=\x82\xd3\xe4\x93\x02\x37\x12\x35/v1beta1/{resource=projects/*/secrets/*}:getIamPolicy\x12\xb1\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse"F\x82\xd3\xe4\x93\x02@";/v1beta1/{resource=projects/*/secrets/*}:testIamPermissions:\x01*\x1aP\xca\x41\x1csecretmanager.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\x84\x02\n&com.google.cloud.secretmanager.v1beta1B\x0cServiceProtoP\x01ZOgoogle.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1;secretmanager\xf8\x01\x01\xa2\x02\x03GSM\xaa\x02"Google.Cloud.SecretManager.V1Beta1\xca\x02"Google\\Cloud\\SecretManager\\V1beta1\xea\x02%Google::Cloud::SecretManager::V1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - ], -) - - -_LISTSECRETSREQUEST = _descriptor.Descriptor( - name="ListSecretsRequest", - full_name="google.cloud.secrets.v1beta1.ListSecretsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secrets.v1beta1.ListSecretsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A-\n+cloudresourcemanager.googleapis.com/Project", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.secrets.v1beta1.ListSecretsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.secrets.v1beta1.ListSecretsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=373, - serialized_end=511, -) - - -_LISTSECRETSRESPONSE = _descriptor.Descriptor( - name="ListSecretsResponse", - full_name="google.cloud.secrets.v1beta1.ListSecretsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="secrets", - full_name="google.cloud.secrets.v1beta1.ListSecretsResponse.secrets", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.secrets.v1beta1.ListSecretsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.secrets.v1beta1.ListSecretsResponse.total_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=513, - serialized_end=634, -) - - -_CREATESECRETREQUEST = _descriptor.Descriptor( - name="CreateSecretRequest", - full_name="google.cloud.secrets.v1beta1.CreateSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secrets.v1beta1.CreateSecretRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A-\n+cloudresourcemanager.googleapis.com/Project", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="secret_id", - full_name="google.cloud.secrets.v1beta1.CreateSecretRequest.secret_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="secret", - full_name="google.cloud.secrets.v1beta1.CreateSecretRequest.secret", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=637, - serialized_end=810, -) - - -_ADDSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="AddSecretVersionRequest", - full_name="google.cloud.secrets.v1beta1.AddSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secrets.v1beta1.AddSecretVersionRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="payload", - full_name="google.cloud.secrets.v1beta1.AddSecretVersionRequest.payload", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=813, - serialized_end=966, -) - - -_GETSECRETREQUEST = _descriptor.Descriptor( - name="GetSecretRequest", - full_name="google.cloud.secrets.v1beta1.GetSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.GetSecretRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=968, - serialized_end=1045, -) - - -_LISTSECRETVERSIONSREQUEST = _descriptor.Descriptor( - name="ListSecretVersionsRequest", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1048, - serialized_end=1185, -) - - -_LISTSECRETVERSIONSRESPONSE = _descriptor.Descriptor( - name="ListSecretVersionsResponse", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="versions", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsResponse.versions", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.secrets.v1beta1.ListSecretVersionsResponse.total_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1188, - serialized_end=1324, -) - - -_GETSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="GetSecretVersionRequest", - full_name="google.cloud.secrets.v1beta1.GetSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.GetSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1326, - serialized_end=1417, -) - - -_UPDATESECRETREQUEST = _descriptor.Descriptor( - name="UpdateSecretRequest", - full_name="google.cloud.secrets.v1beta1.UpdateSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="secret", - full_name="google.cloud.secrets.v1beta1.UpdateSecretRequest.secret", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.secrets.v1beta1.UpdateSecretRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1420, - serialized_end=1554, -) - - -_ACCESSSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="AccessSecretVersionRequest", - full_name="google.cloud.secrets.v1beta1.AccessSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.AccessSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1556, - serialized_end=1650, -) - - -_ACCESSSECRETVERSIONRESPONSE = _descriptor.Descriptor( - name="AccessSecretVersionResponse", - full_name="google.cloud.secrets.v1beta1.AccessSecretVersionResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.AccessSecretVersionResponse.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="payload", - full_name="google.cloud.secrets.v1beta1.AccessSecretVersionResponse.payload", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1653, - serialized_end=1807, -) - - -_DELETESECRETREQUEST = _descriptor.Descriptor( - name="DeleteSecretRequest", - full_name="google.cloud.secrets.v1beta1.DeleteSecretRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.DeleteSecretRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#secretmanager.googleapis.com/Secret", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1809, - serialized_end=1889, -) - - -_DISABLESECRETVERSIONREQUEST = _descriptor.Descriptor( - name="DisableSecretVersionRequest", - full_name="google.cloud.secrets.v1beta1.DisableSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.DisableSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1891, - serialized_end=1986, -) - - -_ENABLESECRETVERSIONREQUEST = _descriptor.Descriptor( - name="EnableSecretVersionRequest", - full_name="google.cloud.secrets.v1beta1.EnableSecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.EnableSecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1988, - serialized_end=2082, -) - - -_DESTROYSECRETVERSIONREQUEST = _descriptor.Descriptor( - name="DestroySecretVersionRequest", - full_name="google.cloud.secrets.v1beta1.DestroySecretVersionRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.secrets.v1beta1.DestroySecretVersionRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A,\n*secretmanager.googleapis.com/SecretVersion", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2084, - serialized_end=2179, -) - -_LISTSECRETSRESPONSE.fields_by_name[ - "secrets" -].message_type = ( - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRET -) -_CREATESECRETREQUEST.fields_by_name[ - "secret" -].message_type = ( - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRET -) -_ADDSECRETVERSIONREQUEST.fields_by_name[ - "payload" -].message_type = ( - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETPAYLOAD -) -_LISTSECRETVERSIONSRESPONSE.fields_by_name[ - "versions" -].message_type = ( - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETVERSION -) -_UPDATESECRETREQUEST.fields_by_name[ - "secret" -].message_type = ( - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRET -) -_UPDATESECRETREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_ACCESSSECRETVERSIONRESPONSE.fields_by_name[ - "payload" -].message_type = ( - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETPAYLOAD -) -DESCRIPTOR.message_types_by_name["ListSecretsRequest"] = _LISTSECRETSREQUEST -DESCRIPTOR.message_types_by_name["ListSecretsResponse"] = _LISTSECRETSRESPONSE -DESCRIPTOR.message_types_by_name["CreateSecretRequest"] = _CREATESECRETREQUEST -DESCRIPTOR.message_types_by_name["AddSecretVersionRequest"] = _ADDSECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name["GetSecretRequest"] = _GETSECRETREQUEST -DESCRIPTOR.message_types_by_name[ - "ListSecretVersionsRequest" -] = _LISTSECRETVERSIONSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListSecretVersionsResponse" -] = _LISTSECRETVERSIONSRESPONSE -DESCRIPTOR.message_types_by_name["GetSecretVersionRequest"] = _GETSECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name["UpdateSecretRequest"] = _UPDATESECRETREQUEST -DESCRIPTOR.message_types_by_name[ - "AccessSecretVersionRequest" -] = _ACCESSSECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name[ - "AccessSecretVersionResponse" -] = _ACCESSSECRETVERSIONRESPONSE -DESCRIPTOR.message_types_by_name["DeleteSecretRequest"] = _DELETESECRETREQUEST -DESCRIPTOR.message_types_by_name[ - "DisableSecretVersionRequest" -] = _DISABLESECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name[ - "EnableSecretVersionRequest" -] = _ENABLESECRETVERSIONREQUEST -DESCRIPTOR.message_types_by_name[ - "DestroySecretVersionRequest" -] = _DESTROYSECRETVERSIONREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListSecretsRequest = _reflection.GeneratedProtocolMessageType( - "ListSecretsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETSREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.ListSecrets][google.cloud.se - crets.v1beta1.SecretManagerService.ListSecrets]. - - Attributes: - parent: - Required. The resource name of the project associated with the - [Secrets][google.cloud.secrets.v1beta1.Secret], in the format - ``projects/*``. - page_size: - Optional. The maximum number of results to be returned in a - single page. If set to 0, the server decides the number of - results to return. If the number is greater than 25000, it is - capped at 25000. - page_token: - Optional. Pagination token, returned earlier via [ListSecretsR - esponse.next_page_token][google.cloud.secrets.v1beta1.ListSecr - etsResponse.next_page_token]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.ListSecretsRequest) - }, -) -_sym_db.RegisterMessage(ListSecretsRequest) - -ListSecretsResponse = _reflection.GeneratedProtocolMessageType( - "ListSecretsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETSRESPONSE, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Response message for [SecretManagerService.ListSecrets][google.cloud.s - ecrets.v1beta1.SecretManagerService.ListSecrets]. - - Attributes: - secrets: - The list of [Secrets][google.cloud.secrets.v1beta1.Secret] - sorted in reverse by create_time (newest first). - next_page_token: - A token to retrieve the next page of results. Pass this value - in [ListSecretsRequest.page_token][google.cloud.secrets.v1beta - 1.ListSecretsRequest.page_token] to retrieve the next page. - total_size: - The total number of - [Secrets][google.cloud.secrets.v1beta1.Secret]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.ListSecretsResponse) - }, -) -_sym_db.RegisterMessage(ListSecretsResponse) - -CreateSecretRequest = _reflection.GeneratedProtocolMessageType( - "CreateSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATESECRETREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.CreateSecret][google.cloud.s - ecrets.v1beta1.SecretManagerService.CreateSecret]. - - Attributes: - parent: - Required. The resource name of the project to associate with - the [Secret][google.cloud.secrets.v1beta1.Secret], in the - format ``projects/*``. - secret_id: - Required. This must be unique within the project. A secret ID - is a string with a maximum length of 255 characters and can - contain uppercase and lowercase letters, numerals, and the - hyphen (``-``) and underscore (``_``) characters. - secret: - Required. A [Secret][google.cloud.secrets.v1beta1.Secret] with - initial field values. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.CreateSecretRequest) - }, -) -_sym_db.RegisterMessage(CreateSecretRequest) - -AddSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "AddSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _ADDSECRETVERSIONREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.AddSecretVersion][google.clo - ud.secrets.v1beta1.SecretManagerService.AddSecretVersion]. - - Attributes: - parent: - Required. The resource name of the - [Secret][google.cloud.secrets.v1beta1.Secret] to associate - with the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in - the format ``projects/*/secrets/*``. - payload: - Required. The secret payload of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.AddSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(AddSecretVersionRequest) - -GetSecretRequest = _reflection.GeneratedProtocolMessageType( - "GetSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSECRETREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.GetSecret][google.cloud.secr - ets.v1beta1.SecretManagerService.GetSecret]. - - Attributes: - name: - Required. The resource name of the - [Secret][google.cloud.secrets.v1beta1.Secret], in the format - ``projects/*/secrets/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.GetSecretRequest) - }, -) -_sym_db.RegisterMessage(GetSecretRequest) - -ListSecretVersionsRequest = _reflection.GeneratedProtocolMessageType( - "ListSecretVersionsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETVERSIONSREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.ListSecretVersions][google.c - loud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. - - Attributes: - parent: - Required. The resource name of the - [Secret][google.cloud.secrets.v1beta1.Secret] associated with - the - [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] - to list, in the format ``projects/*/secrets/*``. - page_size: - Optional. The maximum number of results to be returned in a - single page. If set to 0, the server decides the number of - results to return. If the number is greater than 25000, it is - capped at 25000. - page_token: - Optional. Pagination token, returned earlier via - ListSecretVersionsResponse.next_page_token][]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.ListSecretVersionsRequest) - }, -) -_sym_db.RegisterMessage(ListSecretVersionsRequest) - -ListSecretVersionsResponse = _reflection.GeneratedProtocolMessageType( - "ListSecretVersionsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSECRETVERSIONSRESPONSE, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Response message for [SecretManagerService.ListSecretVersions][google. - cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. - - Attributes: - versions: - The list of - [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] - sorted in reverse by create_time (newest first). - next_page_token: - A token to retrieve the next page of results. Pass this value - in [ListSecretVersionsRequest.page_token][google.cloud.secrets - .v1beta1.ListSecretVersionsRequest.page_token] to retrieve the - next page. - total_size: - The total number of - [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.ListSecretVersionsResponse) - }, -) -_sym_db.RegisterMessage(ListSecretVersionsResponse) - -GetSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "GetSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSECRETVERSIONREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.GetSecretVersion][google.clo - ud.secrets.v1beta1.SecretManagerService.GetSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in - the format ``projects/*/secrets/*/versions/*``. - ``projects/*/secrets/*/versions/latest`` is an alias to the - ``latest`` - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.GetSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(GetSecretVersionRequest) - -UpdateSecretRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESECRETREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.UpdateSecret][google.cloud.s - ecrets.v1beta1.SecretManagerService.UpdateSecret]. - - Attributes: - secret: - Required. [Secret][google.cloud.secrets.v1beta1.Secret] with - updated field values. - update_mask: - Required. Specifies the fields to be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.UpdateSecretRequest) - }, -) -_sym_db.RegisterMessage(UpdateSecretRequest) - -AccessSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "AccessSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _ACCESSSECRETVERSIONREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.AccessSecretVersion][google. - cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in - the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.AccessSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(AccessSecretVersionRequest) - -AccessSecretVersionResponse = _reflection.GeneratedProtocolMessageType( - "AccessSecretVersionResponse", - (_message.Message,), - { - "DESCRIPTOR": _ACCESSSECRETVERSIONRESPONSE, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Response message for [SecretManagerService.AccessSecretVersion][google - .cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. - - Attributes: - name: - The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] in - the format ``projects/*/secrets/*/versions/*``. - payload: - Secret payload - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.AccessSecretVersionResponse) - }, -) -_sym_db.RegisterMessage(AccessSecretVersionResponse) - -DeleteSecretRequest = _reflection.GeneratedProtocolMessageType( - "DeleteSecretRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETESECRETREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.DeleteSecret][google.cloud.s - ecrets.v1beta1.SecretManagerService.DeleteSecret]. - - Attributes: - name: - Required. The resource name of the - [Secret][google.cloud.secrets.v1beta1.Secret] to delete in the - format ``projects/*/secrets/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.DeleteSecretRequest) - }, -) -_sym_db.RegisterMessage(DeleteSecretRequest) - -DisableSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "DisableSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _DISABLESECRETVERSIONREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.DisableSecretVersion][google - .cloud.secrets.v1beta1.SecretManagerService.DisableSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to - disable in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.DisableSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(DisableSecretVersionRequest) - -EnableSecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "EnableSecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _ENABLESECRETVERSIONREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.EnableSecretVersion][google. - cloud.secrets.v1beta1.SecretManagerService.EnableSecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to - enable in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.EnableSecretVersionRequest) - }, -) -_sym_db.RegisterMessage(EnableSecretVersionRequest) - -DestroySecretVersionRequest = _reflection.GeneratedProtocolMessageType( - "DestroySecretVersionRequest", - (_message.Message,), - { - "DESCRIPTOR": _DESTROYSECRETVERSIONREQUEST, - "__module__": "google.cloud.secrets_v1beta1.proto.service_pb2", - "__doc__": """Request message for [SecretManagerService.DestroySecretVersion][google - .cloud.secrets.v1beta1.SecretManagerService.DestroySecretVersion]. - - Attributes: - name: - Required. The resource name of the - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to - destroy in the format ``projects/*/secrets/*/versions/*``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.secrets.v1beta1.DestroySecretVersionRequest) - }, -) -_sym_db.RegisterMessage(DestroySecretVersionRequest) - - -DESCRIPTOR._options = None -_LISTSECRETSREQUEST.fields_by_name["parent"]._options = None -_LISTSECRETSREQUEST.fields_by_name["page_size"]._options = None -_LISTSECRETSREQUEST.fields_by_name["page_token"]._options = None -_CREATESECRETREQUEST.fields_by_name["parent"]._options = None -_CREATESECRETREQUEST.fields_by_name["secret_id"]._options = None -_CREATESECRETREQUEST.fields_by_name["secret"]._options = None -_ADDSECRETVERSIONREQUEST.fields_by_name["parent"]._options = None -_ADDSECRETVERSIONREQUEST.fields_by_name["payload"]._options = None -_GETSECRETREQUEST.fields_by_name["name"]._options = None -_LISTSECRETVERSIONSREQUEST.fields_by_name["parent"]._options = None -_LISTSECRETVERSIONSREQUEST.fields_by_name["page_size"]._options = None -_LISTSECRETVERSIONSREQUEST.fields_by_name["page_token"]._options = None -_GETSECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_UPDATESECRETREQUEST.fields_by_name["secret"]._options = None -_UPDATESECRETREQUEST.fields_by_name["update_mask"]._options = None -_ACCESSSECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_ACCESSSECRETVERSIONRESPONSE.fields_by_name["name"]._options = None -_DELETESECRETREQUEST.fields_by_name["name"]._options = None -_DISABLESECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_ENABLESECRETVERSIONREQUEST.fields_by_name["name"]._options = None -_DESTROYSECRETVERSIONREQUEST.fields_by_name["name"]._options = None - -_SECRETMANAGERSERVICE = _descriptor.ServiceDescriptor( - name="SecretManagerService", - full_name="google.cloud.secrets.v1beta1.SecretManagerService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\034secretmanager.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=2182, - serialized_end=5001, - methods=[ - _descriptor.MethodDescriptor( - name="ListSecrets", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets", - index=0, - containing_service=None, - input_type=_LISTSECRETSREQUEST, - output_type=_LISTSECRETSRESPONSE, - serialized_options=b"\202\323\344\223\002&\022$/v1beta1/{parent=projects/*}/secrets\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateSecret", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.CreateSecret", - index=1, - containing_service=None, - input_type=_CREATESECRETREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRET, - serialized_options=b'\202\323\344\223\002."$/v1beta1/{parent=projects/*}/secrets:\006secret\332A\027parent,secret_id,secret', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AddSecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.AddSecretVersion", - index=2, - containing_service=None, - input_type=_ADDSECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\0026"1/v1beta1/{parent=projects/*/secrets/*}:addVersion:\001*\332A\016parent,payload', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSecret", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.GetSecret", - index=3, - containing_service=None, - input_type=_GETSECRETREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRET, - serialized_options=b"\202\323\344\223\002&\022$/v1beta1/{name=projects/*/secrets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSecret", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.UpdateSecret", - index=4, - containing_service=None, - input_type=_UPDATESECRETREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRET, - serialized_options=b"\202\323\344\223\00252+/v1beta1/{secret.name=projects/*/secrets/*}:\006secret\332A\022secret,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteSecret", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.DeleteSecret", - index=5, - containing_service=None, - input_type=_DELETESECRETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002&*$/v1beta1/{name=projects/*/secrets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListSecretVersions", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions", - index=6, - containing_service=None, - input_type=_LISTSECRETVERSIONSREQUEST, - output_type=_LISTSECRETVERSIONSRESPONSE, - serialized_options=b"\202\323\344\223\0021\022//v1beta1/{parent=projects/*/secrets/*}/versions\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.GetSecretVersion", - index=7, - containing_service=None, - input_type=_GETSECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b"\202\323\344\223\0021\022//v1beta1/{name=projects/*/secrets/*/versions/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AccessSecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion", - index=8, - containing_service=None, - input_type=_ACCESSSECRETVERSIONREQUEST, - output_type=_ACCESSSECRETVERSIONRESPONSE, - serialized_options=b"\202\323\344\223\0028\0226/v1beta1/{name=projects/*/secrets/*/versions/*}:access\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DisableSecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.DisableSecretVersion", - index=9, - containing_service=None, - input_type=_DISABLESECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\002<"7/v1beta1/{name=projects/*/secrets/*/versions/*}:disable:\001*\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="EnableSecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.EnableSecretVersion", - index=10, - containing_service=None, - input_type=_ENABLESECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\002;"6/v1beta1/{name=projects/*/secrets/*/versions/*}:enable:\001*\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DestroySecretVersion", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.DestroySecretVersion", - index=11, - containing_service=None, - input_type=_DESTROYSECRETVERSIONREQUEST, - output_type=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2._SECRETVERSION, - serialized_options=b'\202\323\344\223\002<"7/v1beta1/{name=projects/*/secrets/*/versions/*}:destroy:\001*\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetIamPolicy", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.SetIamPolicy", - index=12, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._SETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002:"5/v1beta1/{resource=projects/*/secrets/*}:setIamPolicy:\001*', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetIamPolicy", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.GetIamPolicy", - index=13, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._GETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b"\202\323\344\223\0027\0225/v1beta1/{resource=projects/*/secrets/*}:getIamPolicy", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="TestIamPermissions", - full_name="google.cloud.secrets.v1beta1.SecretManagerService.TestIamPermissions", - index=14, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSREQUEST, - output_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSRESPONSE, - serialized_options=b'\202\323\344\223\002@";/v1beta1/{resource=projects/*/secrets/*}:testIamPermissions:\001*', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_SECRETMANAGERSERVICE) - -DESCRIPTOR.services_by_name["SecretManagerService"] = _SECRETMANAGERSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/secretmanager_v1beta1/proto/service_pb2_grpc.py b/google/cloud/secretmanager_v1beta1/proto/service_pb2_grpc.py deleted file mode 100644 index c339203..0000000 --- a/google/cloud/secretmanager_v1beta1/proto/service_pb2_grpc.py +++ /dev/null @@ -1,761 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.secretmanager_v1beta1.proto import ( - resources_pb2 as google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2, -) -from google.cloud.secretmanager_v1beta1.proto import ( - service_pb2 as google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class SecretManagerServiceStub(object): - """`projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - * [Secret][google.cloud.secrets.v1beta1.Secret] - * [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListSecrets = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecrets", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretsResponse.FromString, - ) - self.CreateSecret = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/CreateSecret", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.CreateSecretRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.FromString, - ) - self.AddSecretVersion = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/AddSecretVersion", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AddSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.GetSecret = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecret", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.GetSecretRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.FromString, - ) - self.UpdateSecret = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/UpdateSecret", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.UpdateSecretRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.FromString, - ) - self.DeleteSecret = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/DeleteSecret", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DeleteSecretRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListSecretVersions = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecretVersions", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretVersionsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretVersionsResponse.FromString, - ) - self.GetSecretVersion = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecretVersion", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.GetSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.AccessSecretVersion = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/AccessSecretVersion", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AccessSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AccessSecretVersionResponse.FromString, - ) - self.DisableSecretVersion = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/DisableSecretVersion", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DisableSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.EnableSecretVersion = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/EnableSecretVersion", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.EnableSecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.DestroySecretVersion = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/DestroySecretVersion", - request_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DestroySecretVersionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - ) - self.SetIamPolicy = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/SetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.GetIamPolicy = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/GetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.TestIamPermissions = channel.unary_unary( - "/google.cloud.secrets.v1beta1.SecretManagerService/TestIamPermissions", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - ) - - -class SecretManagerServiceServicer(object): - """`projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - * [Secret][google.cloud.secrets.v1beta1.Secret] - * [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] - """ - - def ListSecrets(self, request, context): - """Lists [Secrets][google.cloud.secrets.v1beta1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateSecret(self, request, context): - """Creates a new [Secret][google.cloud.secrets.v1beta1.Secret] containing no [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AddSecretVersion(self, request, context): - """Creates a new [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] containing secret data and attaches - it to an existing [Secret][google.cloud.secrets.v1beta1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSecret(self, request, context): - """Gets metadata for a given [Secret][google.cloud.secrets.v1beta1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSecret(self, request, context): - """Updates metadata of an existing [Secret][google.cloud.secrets.v1beta1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteSecret(self, request, context): - """Deletes a [Secret][google.cloud.secrets.v1beta1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListSecretVersions(self, request, context): - """Lists [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. This call does not return secret - data. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSecretVersion(self, request, context): - """Gets metadata for a [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - `projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AccessSecretVersion(self, request, context): - """Accesses a [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. This call returns the secret data. - - `projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DisableSecretVersion(self, request, context): - """Disables a [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Sets the [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to - [DISABLED][google.cloud.secrets.v1beta1.SecretVersion.State.DISABLED]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def EnableSecretVersion(self, request, context): - """Enables a [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Sets the [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to - [ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DestroySecretVersion(self, request, context): - """Destroys a [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Sets the [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to - [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED] and irrevocably destroys the - secret data. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetIamPolicy(self, request, context): - """Sets the access control policy on the specified secret. Replaces any - existing policy. - - Permissions on [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] are enforced according - to the policy set on the associated [Secret][google.cloud.secrets.v1beta1.Secret]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetIamPolicy(self, request, context): - """Gets the access control policy for a secret. - Returns empty policy if the secret exists and does not have a policy set. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def TestIamPermissions(self, request, context): - """Returns permissions that a caller has for the specified secret. - If the secret does not exist, this call returns an empty set of - permissions, not a NOT_FOUND error. - - Note: This operation is designed to be used for building permission-aware - UIs and command-line tools, not for authorization checking. This operation - may "fail open" without warning. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_SecretManagerServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListSecrets": grpc.unary_unary_rpc_method_handler( - servicer.ListSecrets, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretsRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretsResponse.SerializeToString, - ), - "CreateSecret": grpc.unary_unary_rpc_method_handler( - servicer.CreateSecret, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.CreateSecretRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.SerializeToString, - ), - "AddSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.AddSecretVersion, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AddSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "GetSecret": grpc.unary_unary_rpc_method_handler( - servicer.GetSecret, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.GetSecretRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.SerializeToString, - ), - "UpdateSecret": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSecret, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.UpdateSecretRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.SerializeToString, - ), - "DeleteSecret": grpc.unary_unary_rpc_method_handler( - servicer.DeleteSecret, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DeleteSecretRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListSecretVersions": grpc.unary_unary_rpc_method_handler( - servicer.ListSecretVersions, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretVersionsRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretVersionsResponse.SerializeToString, - ), - "GetSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.GetSecretVersion, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.GetSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "AccessSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.AccessSecretVersion, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AccessSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AccessSecretVersionResponse.SerializeToString, - ), - "DisableSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.DisableSecretVersion, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DisableSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "EnableSecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.EnableSecretVersion, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.EnableSecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "DestroySecretVersion": grpc.unary_unary_rpc_method_handler( - servicer.DestroySecretVersion, - request_deserializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DestroySecretVersionRequest.FromString, - response_serializer=google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.SerializeToString, - ), - "SetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.SetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "GetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.GetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "TestIamPermissions": grpc.unary_unary_rpc_method_handler( - servicer.TestIamPermissions, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.secrets.v1beta1.SecretManagerService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class SecretManagerService(object): - """`projects/*/secrets/*/versions/latest` is an alias to the `latest` - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. - - Secret Manager Service - - Manages secrets and operations using those secrets. Implements a REST - model with the following objects: - - * [Secret][google.cloud.secrets.v1beta1.Secret] - * [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] - """ - - @staticmethod - def ListSecrets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecrets", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretsRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/CreateSecret", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.CreateSecretRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AddSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/AddSecretVersion", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AddSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecret", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.GetSecretRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/UpdateSecret", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.UpdateSecretRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.Secret.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteSecret( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/DeleteSecret", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DeleteSecretRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListSecretVersions( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecretVersions", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretVersionsRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.ListSecretVersionsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecretVersion", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.GetSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AccessSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/AccessSecretVersion", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AccessSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.AccessSecretVersionResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DisableSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/DisableSecretVersion", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DisableSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def EnableSecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/EnableSecretVersion", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.EnableSecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DestroySecretVersion( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/DestroySecretVersion", - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_service__pb2.DestroySecretVersionRequest.SerializeToString, - google_dot_cloud_dot_secrets__v1beta1_dot_proto_dot_resources__pb2.SecretVersion.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/SetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/GetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def TestIamPermissions( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.secrets.v1beta1.SecretManagerService/TestIamPermissions", - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/secretmanager_v1beta1/py.typed b/google/cloud/secretmanager_v1beta1/py.typed new file mode 100644 index 0000000..188cc03 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-secretmanager package uses inline types. diff --git a/google/cloud/__init__.py b/google/cloud/secretmanager_v1beta1/services/__init__.py similarity index 71% rename from google/cloud/__init__.py rename to google/cloud/secretmanager_v1beta1/services/__init__.py index 9a1b64a..42ffdf2 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/secretmanager_v1beta1/services/__init__.py @@ -1,24 +1,16 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - - __path__ = pkgutil.extend_path(__path__, __name__) +# diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/__init__.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/__init__.py new file mode 100644 index 0000000..5407ee8 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SecretManagerServiceClient +from .async_client import SecretManagerServiceAsyncClient + +__all__ = ( + "SecretManagerServiceClient", + "SecretManagerServiceAsyncClient", +) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/async_client.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/async_client.py new file mode 100644 index 0000000..fb2567e --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/async_client.py @@ -0,0 +1,1419 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.secretmanager_v1beta1.services.secret_manager_service import pagers +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport +from .client import SecretManagerServiceClient + + +class SecretManagerServiceAsyncClient: + """Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secrets.v1beta1.Secret] + - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + """ + + _client: SecretManagerServiceClient + + DEFAULT_ENDPOINT = SecretManagerServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecretManagerServiceClient.DEFAULT_MTLS_ENDPOINT + + secret_path = staticmethod(SecretManagerServiceClient.secret_path) + parse_secret_path = staticmethod(SecretManagerServiceClient.parse_secret_path) + + from_service_account_file = SecretManagerServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecretManagerServiceClient).get_transport_class, + type(SecretManagerServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecretManagerServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the secret manager 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, ~.SecretManagerServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SecretManagerServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_secrets( + self, + request: service.ListSecretsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretsAsyncPager: + r"""Lists [Secrets][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.ListSecretsRequest`): + The request object. Request message for + [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets]. + parent (:class:`str`): + Required. The resource name of the project associated + with the [Secrets][google.cloud.secrets.v1beta1.Secret], + in the format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretsAsyncPager: + Response message for + [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.ListSecretsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_secrets, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSecretsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_secret( + self, + request: service.CreateSecretRequest = None, + *, + parent: str = None, + secret_id: str = None, + secret: resources.Secret = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Creates a new [Secret][google.cloud.secrets.v1beta1.Secret] + containing no + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + + Args: + request (:class:`~.service.CreateSecretRequest`): + The request object. Request message for + [SecretManagerService.CreateSecret][google.cloud.secrets.v1beta1.SecretManagerService.CreateSecret]. + parent (:class:`str`): + Required. The resource name of the project to associate + with the [Secret][google.cloud.secrets.v1beta1.Secret], + in the format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret_id (:class:`str`): + Required. This must be unique within the project. + + A secret ID is a string with a maximum length of 255 + characters and can contain uppercase and lowercase + letters, numerals, and the hyphen (``-``) and underscore + (``_``) characters. + This corresponds to the ``secret_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret (:class:`~.resources.Secret`): + Required. A + [Secret][google.cloud.secrets.v1beta1.Secret] with + initial field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secrets.v1beta1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, secret_id, secret]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.CreateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if secret_id is not None: + request.secret_id = secret_id + if secret is not None: + request.secret = secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def add_secret_version( + self, + request: service.AddSecretVersionRequest = None, + *, + parent: str = None, + payload: resources.SecretPayload = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Creates a new + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.AddSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AddSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AddSecretVersion]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] to + associate with the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`~.resources.SecretPayload`): + Required. The secret payload of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, payload]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.AddSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_secret( + self, + request: service.GetSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Gets metadata for a given + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.GetSecretRequest`): + The request object. Request message for + [SecretManagerService.GetSecret][google.cloud.secrets.v1beta1.SecretManagerService.GetSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret], in the + format ``projects/*/secrets/*``. + 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: + ~.resources.Secret: + A [Secret][google.cloud.secrets.v1beta1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GetSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_secret( + self, + request: service.UpdateSecretRequest = None, + *, + secret: resources.Secret = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Updates metadata of an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.UpdateSecretRequest`): + The request object. Request message for + [SecretManagerService.UpdateSecret][google.cloud.secrets.v1beta1.SecretManagerService.UpdateSecret]. + secret (:class:`~.resources.Secret`): + Required. [Secret][google.cloud.secrets.v1beta1.Secret] + with updated field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Specifies the fields to be + updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secrets.v1beta1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([secret, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.UpdateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if secret is not None: + request.secret = secret + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("secret.name", request.secret.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_secret( + self, + request: service.DeleteSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.DeleteSecretRequest`): + The request object. Request message for + [SecretManagerService.DeleteSecret][google.cloud.secrets.v1beta1.SecretManagerService.DeleteSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] to delete + in the format ``projects/*/secrets/*``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.DeleteSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_secret, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_secret_versions( + self, + request: service.ListSecretVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretVersionsAsyncPager: + r"""Lists + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + This call does not return secret data. + + Args: + request (:class:`~.service.ListSecretVersionsRequest`): + The request object. Request message for + [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] associated + with the + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + to list, in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretVersionsAsyncPager: + Response message for + [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.ListSecretVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_secret_versions, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSecretVersionsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_secret_version( + self, + request: service.GetSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Gets metadata for a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Args: + request (:class:`~.service.GetSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.GetSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.GetSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + ``projects/*/secrets/*/versions/latest`` is an alias to + the ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GetSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def access_secret_version( + self, + request: service.AccessSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AccessSecretVersionResponse: + r"""Accesses a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Args: + request (:class:`~.service.AccessSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + 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: + ~.service.AccessSecretVersionResponse: + Response message for + [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.AccessSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.access_secret_version, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Unknown, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def disable_secret_version( + self, + request: service.DisableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Disables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DISABLED][google.cloud.secrets.v1beta1.SecretVersion.State.DISABLED]. + + Args: + request (:class:`~.service.DisableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DisableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DisableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to disable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.DisableSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.disable_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def enable_secret_version( + self, + request: service.EnableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Enables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED]. + + Args: + request (:class:`~.service.EnableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.EnableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.EnableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to enable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.EnableSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.enable_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def destroy_secret_version( + self, + request: service.DestroySecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Destroys a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Args: + request (:class:`~.service.DestroySecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DestroySecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DestroySecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to destroy in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.DestroySecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.destroy_secret_version, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] are + enforced according to the policy set on the associated + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-secretmanager", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecretManagerServiceAsyncClient",) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/client.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/client.py new file mode 100644 index 0000000..0cf0016 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/client.py @@ -0,0 +1,1582 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.secretmanager_v1beta1.services.secret_manager_service import pagers +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecretManagerServiceGrpcTransport +from .transports.grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport + + +class SecretManagerServiceClientMeta(type): + """Metaclass for the SecretManagerService 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[SecretManagerServiceTransport]] + _transport_registry["grpc"] = SecretManagerServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SecretManagerServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[SecretManagerServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SecretManagerServiceClient(metaclass=SecretManagerServiceClientMeta): + """Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secrets.v1beta1.Secret] + - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "secretmanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def secret_path(project: str, secret: str,) -> str: + """Return a fully-qualified secret string.""" + return "projects/{project}/secrets/{secret}".format( + project=project, secret=secret, + ) + + @staticmethod + def parse_secret_path(path: str) -> Dict[str, str]: + """Parse a secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecretManagerServiceTransport] = None, + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the secret manager 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, ~.SecretManagerServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + 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 = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecretManagerServiceTransport): + # transport is a SecretManagerServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_secrets( + self, + request: service.ListSecretsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretsPager: + r"""Lists [Secrets][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.ListSecretsRequest`): + The request object. Request message for + [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets]. + parent (:class:`str`): + Required. The resource name of the project associated + with the [Secrets][google.cloud.secrets.v1beta1.Secret], + in the format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretsPager: + Response message for + [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets]. + + 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 service.ListSecretsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSecretsRequest): + request = service.ListSecretsRequest(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_secrets] + + # Certain fields should be provided 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.ListSecretsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def create_secret( + self, + request: service.CreateSecretRequest = None, + *, + parent: str = None, + secret_id: str = None, + secret: resources.Secret = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Creates a new [Secret][google.cloud.secrets.v1beta1.Secret] + containing no + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + + Args: + request (:class:`~.service.CreateSecretRequest`): + The request object. Request message for + [SecretManagerService.CreateSecret][google.cloud.secrets.v1beta1.SecretManagerService.CreateSecret]. + parent (:class:`str`): + Required. The resource name of the project to associate + with the [Secret][google.cloud.secrets.v1beta1.Secret], + in the format ``projects/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret_id (:class:`str`): + Required. This must be unique within the project. + + A secret ID is a string with a maximum length of 255 + characters and can contain uppercase and lowercase + letters, numerals, and the hyphen (``-``) and underscore + (``_``) characters. + This corresponds to the ``secret_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + secret (:class:`~.resources.Secret`): + Required. A + [Secret][google.cloud.secrets.v1beta1.Secret] with + initial field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secrets.v1beta1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, secret_id, secret]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.CreateSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateSecretRequest): + request = service.CreateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if secret_id is not None: + request.secret_id = secret_id + if secret is not None: + request.secret = secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_secret] + + # Certain fields should be provided 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 add_secret_version( + self, + request: service.AddSecretVersionRequest = None, + *, + parent: str = None, + payload: resources.SecretPayload = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Creates a new + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.AddSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AddSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AddSecretVersion]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] to + associate with the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`~.resources.SecretPayload`): + Required. The secret payload of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, payload]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.AddSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.AddSecretVersionRequest): + request = service.AddSecretVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_secret_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_secret( + self, + request: service.GetSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Gets metadata for a given + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.GetSecretRequest`): + The request object. Request message for + [SecretManagerService.GetSecret][google.cloud.secrets.v1beta1.SecretManagerService.GetSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret], in the + format ``projects/*/secrets/*``. + 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: + ~.resources.Secret: + A [Secret][google.cloud.secrets.v1beta1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetSecretRequest): + request = service.GetSecretRequest(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_secret] + + # 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 update_secret( + self, + request: service.UpdateSecretRequest = None, + *, + secret: resources.Secret = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Secret: + r"""Updates metadata of an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.UpdateSecretRequest`): + The request object. Request message for + [SecretManagerService.UpdateSecret][google.cloud.secrets.v1beta1.SecretManagerService.UpdateSecret]. + secret (:class:`~.resources.Secret`): + Required. [Secret][google.cloud.secrets.v1beta1.Secret] + with updated field values. + This corresponds to the ``secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. Specifies the fields to be + updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Secret: + A [Secret][google.cloud.secrets.v1beta1.Secret] is a + logical secret whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made + up of zero or more + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([secret, 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 service.UpdateSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateSecretRequest): + request = service.UpdateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if secret is not None: + request.secret = secret + 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_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("secret.name", request.secret.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_secret( + self, + request: service.DeleteSecretRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.service.DeleteSecretRequest`): + The request object. Request message for + [SecretManagerService.DeleteSecret][google.cloud.secrets.v1beta1.SecretManagerService.DeleteSecret]. + name (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] to delete + in the format ``projects/*/secrets/*``. + 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 service.DeleteSecretRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteSecretRequest): + request = service.DeleteSecretRequest(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_secret] + + # 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 list_secret_versions( + self, + request: service.ListSecretVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecretVersionsPager: + r"""Lists + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + This call does not return secret data. + + Args: + request (:class:`~.service.ListSecretVersionsRequest`): + The request object. Request message for + [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] associated + with the + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + to list, in the format ``projects/*/secrets/*``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSecretVersionsPager: + Response message for + [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. + + 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 service.ListSecretVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListSecretVersionsRequest): + request = service.ListSecretVersionsRequest(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_secret_versions] + + # Certain fields should be provided 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.ListSecretVersionsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_secret_version( + self, + request: service.GetSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Gets metadata for a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Args: + request (:class:`~.service.GetSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.GetSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.GetSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + ``projects/*/secrets/*/versions/latest`` is an alias to + the ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetSecretVersionRequest): + request = service.GetSecretVersionRequest(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_secret_version] + + # 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 access_secret_version( + self, + request: service.AccessSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AccessSecretVersionResponse: + r"""Accesses a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Args: + request (:class:`~.service.AccessSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + 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: + ~.service.AccessSecretVersionResponse: + Response message for + [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.AccessSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.AccessSecretVersionRequest): + request = service.AccessSecretVersionRequest(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.access_secret_version] + + # 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 disable_secret_version( + self, + request: service.DisableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Disables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DISABLED][google.cloud.secrets.v1beta1.SecretVersion.State.DISABLED]. + + Args: + request (:class:`~.service.DisableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DisableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DisableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to disable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.DisableSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DisableSecretVersionRequest): + request = service.DisableSecretVersionRequest(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.disable_secret_version] + + # 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 enable_secret_version( + self, + request: service.EnableSecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Enables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED]. + + Args: + request (:class:`~.service.EnableSecretVersionRequest`): + The request object. Request message for + [SecretManagerService.EnableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.EnableSecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to enable in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.EnableSecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.EnableSecretVersionRequest): + request = service.EnableSecretVersionRequest(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.enable_secret_version] + + # 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 destroy_secret_version( + self, + request: service.DestroySecretVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SecretVersion: + r"""Destroys a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Args: + request (:class:`~.service.DestroySecretVersionRequest`): + The request object. Request message for + [SecretManagerService.DestroySecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DestroySecretVersion]. + name (:class:`str`): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to destroy in the format + ``projects/*/secrets/*/versions/*``. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.DestroySecretVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DestroySecretVersionRequest): + request = service.DestroySecretVersionRequest(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.destroy_secret_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] are + enforced according to the policy set on the associated + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-secretmanager", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecretManagerServiceClient",) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/pagers.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/pagers.py new file mode 100644 index 0000000..db9122e --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/pagers.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service + + +class ListSecretsPager: + """A pager for iterating through ``list_secrets`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``secrets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecrets`` requests and continue to iterate + through the ``secrets`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretsResponse` + 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[..., service.ListSecretsResponse], + request: service.ListSecretsRequest, + response: service.ListSecretsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretsRequest`): + The initial request object. + response (:class:`~.service.ListSecretsResponse`): + 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 = service.ListSecretsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[service.ListSecretsResponse]: + 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[resources.Secret]: + for page in self.pages: + yield from page.secrets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecretsAsyncPager: + """A pager for iterating through ``list_secrets`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``secrets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecrets`` requests and continue to iterate + through the ``secrets`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListSecretsResponse]], + request: service.ListSecretsRequest, + response: service.ListSecretsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretsRequest`): + The initial request object. + response (:class:`~.service.ListSecretsResponse`): + 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 = service.ListSecretsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[service.ListSecretsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[resources.Secret]: + async def async_generator(): + async for page in self.pages: + for response in page.secrets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecretVersionsPager: + """A pager for iterating through ``list_secret_versions`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecretVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretVersionsResponse` + 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[..., service.ListSecretVersionsResponse], + request: service.ListSecretVersionsRequest, + response: service.ListSecretVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretVersionsRequest`): + The initial request object. + response (:class:`~.service.ListSecretVersionsResponse`): + 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 = service.ListSecretVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[service.ListSecretVersionsResponse]: + 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[resources.SecretVersion]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecretVersionsAsyncPager: + """A pager for iterating through ``list_secret_versions`` requests. + + This class thinly wraps an initial + :class:`~.service.ListSecretVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecretVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`~.service.ListSecretVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListSecretVersionsResponse]], + request: service.ListSecretVersionsRequest, + response: service.ListSecretVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.service.ListSecretVersionsRequest`): + The initial request object. + response (:class:`~.service.ListSecretVersionsResponse`): + 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 = service.ListSecretVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[service.ListSecretVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[resources.SecretVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/__init__.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/__init__.py new file mode 100644 index 0000000..71c2343 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SecretManagerServiceTransport +from .grpc import SecretManagerServiceGrpcTransport +from .grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[SecretManagerServiceTransport]] +_transport_registry["grpc"] = SecretManagerServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SecretManagerServiceGrpcAsyncIOTransport + + +__all__ = ( + "SecretManagerServiceTransport", + "SecretManagerServiceGrpcTransport", + "SecretManagerServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/base.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/base.py new file mode 100644 index 0000000..c8544df --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/base.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-secretmanager", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class SecretManagerServiceTransport(abc.ABC): + """Abstract transport class for SecretManagerService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_secrets: gapic_v1.method.wrap_method( + self.list_secrets, default_timeout=60.0, client_info=client_info, + ), + self.create_secret: gapic_v1.method.wrap_method( + self.create_secret, default_timeout=60.0, client_info=client_info, + ), + self.add_secret_version: gapic_v1.method.wrap_method( + self.add_secret_version, default_timeout=60.0, client_info=client_info, + ), + self.get_secret: gapic_v1.method.wrap_method( + self.get_secret, default_timeout=60.0, client_info=client_info, + ), + self.update_secret: gapic_v1.method.wrap_method( + self.update_secret, default_timeout=60.0, client_info=client_info, + ), + self.delete_secret: gapic_v1.method.wrap_method( + self.delete_secret, default_timeout=60.0, client_info=client_info, + ), + self.list_secret_versions: gapic_v1.method.wrap_method( + self.list_secret_versions, + default_timeout=60.0, + client_info=client_info, + ), + self.get_secret_version: gapic_v1.method.wrap_method( + self.get_secret_version, default_timeout=60.0, client_info=client_info, + ), + self.access_secret_version: gapic_v1.method.wrap_method( + self.access_secret_version, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.Unknown, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_secret_version: gapic_v1.method.wrap_method( + self.disable_secret_version, + default_timeout=60.0, + client_info=client_info, + ), + self.enable_secret_version: gapic_v1.method.wrap_method( + self.enable_secret_version, + default_timeout=60.0, + client_info=client_info, + ), + self.destroy_secret_version: gapic_v1.method.wrap_method( + self.destroy_secret_version, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, default_timeout=60.0, client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, default_timeout=60.0, client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=60.0, + client_info=client_info, + ), + } + + @property + def list_secrets( + self, + ) -> typing.Callable[ + [service.ListSecretsRequest], + typing.Union[ + service.ListSecretsResponse, typing.Awaitable[service.ListSecretsResponse] + ], + ]: + raise NotImplementedError() + + @property + def create_secret( + self, + ) -> typing.Callable[ + [service.CreateSecretRequest], + typing.Union[resources.Secret, typing.Awaitable[resources.Secret]], + ]: + raise NotImplementedError() + + @property + def add_secret_version( + self, + ) -> typing.Callable[ + [service.AddSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def get_secret( + self, + ) -> typing.Callable[ + [service.GetSecretRequest], + typing.Union[resources.Secret, typing.Awaitable[resources.Secret]], + ]: + raise NotImplementedError() + + @property + def update_secret( + self, + ) -> typing.Callable[ + [service.UpdateSecretRequest], + typing.Union[resources.Secret, typing.Awaitable[resources.Secret]], + ]: + raise NotImplementedError() + + @property + def delete_secret( + self, + ) -> typing.Callable[ + [service.DeleteSecretRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_secret_versions( + self, + ) -> typing.Callable[ + [service.ListSecretVersionsRequest], + typing.Union[ + service.ListSecretVersionsResponse, + typing.Awaitable[service.ListSecretVersionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_secret_version( + self, + ) -> typing.Callable[ + [service.GetSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def access_secret_version( + self, + ) -> typing.Callable[ + [service.AccessSecretVersionRequest], + typing.Union[ + service.AccessSecretVersionResponse, + typing.Awaitable[service.AccessSecretVersionResponse], + ], + ]: + raise NotImplementedError() + + @property + def disable_secret_version( + self, + ) -> typing.Callable[ + [service.DisableSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def enable_secret_version( + self, + ) -> typing.Callable[ + [service.EnableSecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def destroy_secret_version( + self, + ) -> typing.Callable[ + [service.DestroySecretVersionRequest], + typing.Union[ + resources.SecretVersion, typing.Awaitable[resources.SecretVersion] + ], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecretManagerServiceTransport",) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/grpc.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/grpc.py new file mode 100644 index 0000000..b022fe4 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/grpc.py @@ -0,0 +1,689 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO + + +class SecretManagerServiceGrpcTransport(SecretManagerServiceTransport): + """gRPC backend transport for SecretManagerService. + + Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secrets.v1beta1.Secret] + - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_secrets( + self, + ) -> Callable[[service.ListSecretsRequest], service.ListSecretsResponse]: + r"""Return a callable for the list secrets method over gRPC. + + Lists [Secrets][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.ListSecretsRequest], + ~.ListSecretsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secrets" not in self._stubs: + self._stubs["list_secrets"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecrets", + request_serializer=service.ListSecretsRequest.serialize, + response_deserializer=service.ListSecretsResponse.deserialize, + ) + return self._stubs["list_secrets"] + + @property + def create_secret( + self, + ) -> Callable[[service.CreateSecretRequest], resources.Secret]: + r"""Return a callable for the create secret method over gRPC. + + Creates a new [Secret][google.cloud.secrets.v1beta1.Secret] + containing no + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + + Returns: + Callable[[~.CreateSecretRequest], + ~.Secret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_secret" not in self._stubs: + self._stubs["create_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/CreateSecret", + request_serializer=service.CreateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["create_secret"] + + @property + def add_secret_version( + self, + ) -> Callable[[service.AddSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the add secret version method over gRPC. + + Creates a new + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.AddSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_secret_version" not in self._stubs: + self._stubs["add_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/AddSecretVersion", + request_serializer=service.AddSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["add_secret_version"] + + @property + def get_secret(self) -> Callable[[service.GetSecretRequest], resources.Secret]: + r"""Return a callable for the get secret method over gRPC. + + Gets metadata for a given + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.GetSecretRequest], + ~.Secret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret" not in self._stubs: + self._stubs["get_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecret", + request_serializer=service.GetSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["get_secret"] + + @property + def update_secret( + self, + ) -> Callable[[service.UpdateSecretRequest], resources.Secret]: + r"""Return a callable for the update secret method over gRPC. + + Updates metadata of an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.UpdateSecretRequest], + ~.Secret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_secret" not in self._stubs: + self._stubs["update_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/UpdateSecret", + request_serializer=service.UpdateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["update_secret"] + + @property + def delete_secret(self) -> Callable[[service.DeleteSecretRequest], empty.Empty]: + r"""Return a callable for the delete secret method over gRPC. + + Deletes a [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.DeleteSecretRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_secret" not in self._stubs: + self._stubs["delete_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/DeleteSecret", + request_serializer=service.DeleteSecretRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_secret"] + + @property + def list_secret_versions( + self, + ) -> Callable[ + [service.ListSecretVersionsRequest], service.ListSecretVersionsResponse + ]: + r"""Return a callable for the list secret versions method over gRPC. + + Lists + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + This call does not return secret data. + + Returns: + Callable[[~.ListSecretVersionsRequest], + ~.ListSecretVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secret_versions" not in self._stubs: + self._stubs["list_secret_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecretVersions", + request_serializer=service.ListSecretVersionsRequest.serialize, + response_deserializer=service.ListSecretVersionsResponse.deserialize, + ) + return self._stubs["list_secret_versions"] + + @property + def get_secret_version( + self, + ) -> Callable[[service.GetSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the get secret version method over gRPC. + + Gets metadata for a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Returns: + Callable[[~.GetSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret_version" not in self._stubs: + self._stubs["get_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecretVersion", + request_serializer=service.GetSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["get_secret_version"] + + @property + def access_secret_version( + self, + ) -> Callable[ + [service.AccessSecretVersionRequest], service.AccessSecretVersionResponse + ]: + r"""Return a callable for the access secret version method over gRPC. + + Accesses a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Returns: + Callable[[~.AccessSecretVersionRequest], + ~.AccessSecretVersionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "access_secret_version" not in self._stubs: + self._stubs["access_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/AccessSecretVersion", + request_serializer=service.AccessSecretVersionRequest.serialize, + response_deserializer=service.AccessSecretVersionResponse.deserialize, + ) + return self._stubs["access_secret_version"] + + @property + def disable_secret_version( + self, + ) -> Callable[[service.DisableSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the disable secret version method over gRPC. + + Disables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DISABLED][google.cloud.secrets.v1beta1.SecretVersion.State.DISABLED]. + + Returns: + Callable[[~.DisableSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_secret_version" not in self._stubs: + self._stubs["disable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/DisableSecretVersion", + request_serializer=service.DisableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["disable_secret_version"] + + @property + def enable_secret_version( + self, + ) -> Callable[[service.EnableSecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the enable secret version method over gRPC. + + Enables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED]. + + Returns: + Callable[[~.EnableSecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_secret_version" not in self._stubs: + self._stubs["enable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/EnableSecretVersion", + request_serializer=service.EnableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["enable_secret_version"] + + @property + def destroy_secret_version( + self, + ) -> Callable[[service.DestroySecretVersionRequest], resources.SecretVersion]: + r"""Return a callable for the destroy secret version method over gRPC. + + Destroys a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Returns: + Callable[[~.DestroySecretVersionRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "destroy_secret_version" not in self._stubs: + self._stubs["destroy_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/DestroySecretVersion", + request_serializer=service.DestroySecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["destroy_secret_version"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] are + enforced according to the policy set on the associated + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SecretManagerServiceGrpcTransport",) diff --git a/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/grpc_asyncio.py b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..4ce9f59 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/services/secret_manager_service/transports/grpc_asyncio.py @@ -0,0 +1,706 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecretManagerServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SecretManagerServiceGrpcTransport + + +class SecretManagerServiceGrpcAsyncIOTransport(SecretManagerServiceTransport): + """gRPC AsyncIO backend transport for SecretManagerService. + + Secret Manager Service + + Manages secrets and operations using those secrets. Implements a + REST model with the following objects: + + - [Secret][google.cloud.secrets.v1beta1.Secret] + - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "secretmanager.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_secrets( + self, + ) -> Callable[[service.ListSecretsRequest], Awaitable[service.ListSecretsResponse]]: + r"""Return a callable for the list secrets method over gRPC. + + Lists [Secrets][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.ListSecretsRequest], + Awaitable[~.ListSecretsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secrets" not in self._stubs: + self._stubs["list_secrets"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecrets", + request_serializer=service.ListSecretsRequest.serialize, + response_deserializer=service.ListSecretsResponse.deserialize, + ) + return self._stubs["list_secrets"] + + @property + def create_secret( + self, + ) -> Callable[[service.CreateSecretRequest], Awaitable[resources.Secret]]: + r"""Return a callable for the create secret method over gRPC. + + Creates a new [Secret][google.cloud.secrets.v1beta1.Secret] + containing no + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + + Returns: + Callable[[~.CreateSecretRequest], + Awaitable[~.Secret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_secret" not in self._stubs: + self._stubs["create_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/CreateSecret", + request_serializer=service.CreateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["create_secret"] + + @property + def add_secret_version( + self, + ) -> Callable[ + [service.AddSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the add secret version method over gRPC. + + Creates a new + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + containing secret data and attaches it to an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.AddSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_secret_version" not in self._stubs: + self._stubs["add_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/AddSecretVersion", + request_serializer=service.AddSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["add_secret_version"] + + @property + def get_secret( + self, + ) -> Callable[[service.GetSecretRequest], Awaitable[resources.Secret]]: + r"""Return a callable for the get secret method over gRPC. + + Gets metadata for a given + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.GetSecretRequest], + Awaitable[~.Secret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret" not in self._stubs: + self._stubs["get_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecret", + request_serializer=service.GetSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["get_secret"] + + @property + def update_secret( + self, + ) -> Callable[[service.UpdateSecretRequest], Awaitable[resources.Secret]]: + r"""Return a callable for the update secret method over gRPC. + + Updates metadata of an existing + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.UpdateSecretRequest], + Awaitable[~.Secret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_secret" not in self._stubs: + self._stubs["update_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/UpdateSecret", + request_serializer=service.UpdateSecretRequest.serialize, + response_deserializer=resources.Secret.deserialize, + ) + return self._stubs["update_secret"] + + @property + def delete_secret( + self, + ) -> Callable[[service.DeleteSecretRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete secret method over gRPC. + + Deletes a [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.DeleteSecretRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_secret" not in self._stubs: + self._stubs["delete_secret"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/DeleteSecret", + request_serializer=service.DeleteSecretRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_secret"] + + @property + def list_secret_versions( + self, + ) -> Callable[ + [service.ListSecretVersionsRequest], + Awaitable[service.ListSecretVersionsResponse], + ]: + r"""Return a callable for the list secret versions method over gRPC. + + Lists + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + This call does not return secret data. + + Returns: + Callable[[~.ListSecretVersionsRequest], + Awaitable[~.ListSecretVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_secret_versions" not in self._stubs: + self._stubs["list_secret_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/ListSecretVersions", + request_serializer=service.ListSecretVersionsRequest.serialize, + response_deserializer=service.ListSecretVersionsResponse.deserialize, + ) + return self._stubs["list_secret_versions"] + + @property + def get_secret_version( + self, + ) -> Callable[ + [service.GetSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the get secret version method over gRPC. + + Gets metadata for a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Returns: + Callable[[~.GetSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_secret_version" not in self._stubs: + self._stubs["get_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/GetSecretVersion", + request_serializer=service.GetSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["get_secret_version"] + + @property + def access_secret_version( + self, + ) -> Callable[ + [service.AccessSecretVersionRequest], + Awaitable[service.AccessSecretVersionResponse], + ]: + r"""Return a callable for the access secret version method over gRPC. + + Accesses a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + This call returns the secret data. + + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Returns: + Callable[[~.AccessSecretVersionRequest], + Awaitable[~.AccessSecretVersionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "access_secret_version" not in self._stubs: + self._stubs["access_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/AccessSecretVersion", + request_serializer=service.AccessSecretVersionRequest.serialize, + response_deserializer=service.AccessSecretVersionResponse.deserialize, + ) + return self._stubs["access_secret_version"] + + @property + def disable_secret_version( + self, + ) -> Callable[ + [service.DisableSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the disable secret version method over gRPC. + + Disables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DISABLED][google.cloud.secrets.v1beta1.SecretVersion.State.DISABLED]. + + Returns: + Callable[[~.DisableSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_secret_version" not in self._stubs: + self._stubs["disable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/DisableSecretVersion", + request_serializer=service.DisableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["disable_secret_version"] + + @property + def enable_secret_version( + self, + ) -> Callable[ + [service.EnableSecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the enable secret version method over gRPC. + + Enables a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED]. + + Returns: + Callable[[~.EnableSecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_secret_version" not in self._stubs: + self._stubs["enable_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/EnableSecretVersion", + request_serializer=service.EnableSecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["enable_secret_version"] + + @property + def destroy_secret_version( + self, + ) -> Callable[ + [service.DestroySecretVersionRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the destroy secret version method over gRPC. + + Destroys a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Sets the + [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to + [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED] + and irrevocably destroys the secret data. + + Returns: + Callable[[~.DestroySecretVersionRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "destroy_secret_version" not in self._stubs: + self._stubs["destroy_secret_version"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/DestroySecretVersion", + request_serializer=service.DestroySecretVersionRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["destroy_secret_version"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified secret. Replaces + any existing policy. + + Permissions on + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] are + enforced according to the policy set on the associated + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a secret. + Returns empty policy if the secret exists and does not + have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has for the specified secret. + If the secret does not exist, this call returns an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for + authorization checking. This operation may "fail open" without + warning. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.secrets.v1beta1.SecretManagerService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SecretManagerServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/secretmanager_v1beta1/types.py b/google/cloud/secretmanager_v1beta1/types.py deleted file mode 100644 index 118d804..0000000 --- a/google/cloud/secretmanager_v1beta1/types.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.secretmanager_v1beta1.proto import resources_pb2 -from google.cloud.secretmanager_v1beta1.proto import service_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - iam_policy_pb2, - options_pb2, - policy_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - expr_pb2, -] - -_local_modules = [ - resources_pb2, - service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.secretmanager_v1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/secretmanager_v1beta1/types/__init__.py b/google/cloud/secretmanager_v1beta1/types/__init__.py new file mode 100644 index 0000000..e26ca04 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/types/__init__.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .resources import ( + Secret, + SecretVersion, + Replication, + SecretPayload, +) +from .service import ( + ListSecretsRequest, + ListSecretsResponse, + CreateSecretRequest, + AddSecretVersionRequest, + GetSecretRequest, + ListSecretVersionsRequest, + ListSecretVersionsResponse, + GetSecretVersionRequest, + UpdateSecretRequest, + AccessSecretVersionRequest, + AccessSecretVersionResponse, + DeleteSecretRequest, + DisableSecretVersionRequest, + EnableSecretVersionRequest, + DestroySecretVersionRequest, +) + + +__all__ = ( + "Secret", + "SecretVersion", + "Replication", + "SecretPayload", + "ListSecretsRequest", + "ListSecretsResponse", + "CreateSecretRequest", + "AddSecretVersionRequest", + "GetSecretRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "GetSecretVersionRequest", + "UpdateSecretRequest", + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "DeleteSecretRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "DestroySecretVersionRequest", +) diff --git a/google/cloud/secretmanager_v1beta1/types/resources.py b/google/cloud/secretmanager_v1beta1/types/resources.py new file mode 100644 index 0000000..05959ea --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/types/resources.py @@ -0,0 +1,195 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.secrets.v1beta1", + manifest={"Secret", "SecretVersion", "Replication", "SecretPayload",}, +) + + +class Secret(proto.Message): + r"""A [Secret][google.cloud.secrets.v1beta1.Secret] is a logical secret + whose value and versions can be accessed. + + A [Secret][google.cloud.secrets.v1beta1.Secret] is made up of zero + or more [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + that represent the secret data. + + Attributes: + name (str): + Output only. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] in the format + ``projects/*/secrets/*``. + replication (~.resources.Replication): + Required. Immutable. The replication policy of the secret + data attached to the + [Secret][google.cloud.secrets.v1beta1.Secret]. + + The replication policy cannot be changed after the Secret + has been created. + create_time (~.timestamp.Timestamp): + Output only. The time at which the + [Secret][google.cloud.secrets.v1beta1.Secret] was created. + labels (Sequence[~.resources.Secret.LabelsEntry]): + The labels assigned to this Secret. + + Label keys must be between 1 and 63 characters long, have a + UTF-8 encoding of maximum 128 bytes, and must conform to the + following PCRE regular expression: + ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}`` + + Label values must be between 0 and 63 characters long, have + a UTF-8 encoding of maximum 128 bytes, and must conform to + the following PCRE regular expression: + ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}`` + + No more than 64 labels can be assigned to a given resource. + """ + + name = proto.Field(proto.STRING, number=1) + + replication = proto.Field(proto.MESSAGE, number=2, message="Replication",) + + create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + labels = proto.MapField(proto.STRING, proto.STRING, number=4) + + +class SecretVersion(proto.Message): + r"""A secret version resource in the Secret Manager API. + + Attributes: + name (str): + Output only. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + IDs in a [Secret][google.cloud.secrets.v1beta1.Secret] start + at 1 and are incremented for each subsequent version of the + secret. + create_time (~.timestamp.Timestamp): + Output only. The time at which the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + was created. + destroy_time (~.timestamp.Timestamp): + Output only. The time this + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + was destroyed. Only present if + [state][google.cloud.secrets.v1beta1.SecretVersion.state] is + [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED]. + state (~.resources.SecretVersion.State): + Output only. The current state of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + """ + + class State(proto.Enum): + r"""The state of a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion], + indicating if it can be accessed. + """ + STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + DESTROYED = 3 + + name = proto.Field(proto.STRING, number=1) + + create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + destroy_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + +class Replication(proto.Message): + r"""A policy that defines the replication configuration of data. + + Attributes: + automatic (~.resources.Replication.Automatic): + The [Secret][google.cloud.secrets.v1beta1.Secret] will + automatically be replicated without any restrictions. + user_managed (~.resources.Replication.UserManaged): + The [Secret][google.cloud.secrets.v1beta1.Secret] will only + be replicated into the locations specified. + """ + + class Automatic(proto.Message): + r"""A replication policy that replicates the + [Secret][google.cloud.secrets.v1beta1.Secret] payload without any + restrictions. + """ + + class UserManaged(proto.Message): + r"""A replication policy that replicates the + [Secret][google.cloud.secrets.v1beta1.Secret] payload into the + locations specified in [Secret.replication.user_managed.replicas][] + + Attributes: + replicas (Sequence[~.resources.Replication.UserManaged.Replica]): + Required. The list of Replicas for this + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Cannot be empty. + """ + + class Replica(proto.Message): + r"""Represents a Replica for this + [Secret][google.cloud.secrets.v1beta1.Secret]. + + Attributes: + location (str): + The canonical IDs of the location to replicate data. For + example: ``"us-east1"``. + """ + + location = proto.Field(proto.STRING, number=1) + + replicas = proto.RepeatedField( + proto.MESSAGE, number=1, message="Replication.UserManaged.Replica", + ) + + automatic = proto.Field( + proto.MESSAGE, number=1, oneof="replication", message=Automatic, + ) + + user_managed = proto.Field( + proto.MESSAGE, number=2, oneof="replication", message=UserManaged, + ) + + +class SecretPayload(proto.Message): + r"""A secret payload resource in the Secret Manager API. This contains + the sensitive secret data that is associated with a + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + + Attributes: + data (bytes): + The secret data. Must be no larger than + 64KiB. + """ + + data = proto.Field(proto.BYTES, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/secretmanager_v1beta1/types/service.py b/google/cloud/secretmanager_v1beta1/types/service.py new file mode 100644 index 0000000..46b1d61 --- /dev/null +++ b/google/cloud/secretmanager_v1beta1/types/service.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.secretmanager_v1beta1.types import resources +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.secrets.v1beta1", + manifest={ + "ListSecretsRequest", + "ListSecretsResponse", + "CreateSecretRequest", + "AddSecretVersionRequest", + "GetSecretRequest", + "ListSecretVersionsRequest", + "ListSecretVersionsResponse", + "GetSecretVersionRequest", + "UpdateSecretRequest", + "AccessSecretVersionRequest", + "AccessSecretVersionResponse", + "DeleteSecretRequest", + "DisableSecretVersionRequest", + "EnableSecretVersionRequest", + "DestroySecretVersionRequest", + }, +) + + +class ListSecretsRequest(proto.Message): + r"""Request message for + [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets]. + + Attributes: + parent (str): + Required. The resource name of the project associated with + the [Secrets][google.cloud.secrets.v1beta1.Secret], in the + format ``projects/*``. + page_size (int): + Optional. The maximum number of results to be + returned in a single page. If set to 0, the + server decides the number of results to return. + If the number is greater than 25000, it is + capped at 25000. + page_token (str): + Optional. Pagination token, returned earlier via + [ListSecretsResponse.next_page_token][google.cloud.secrets.v1beta1.ListSecretsResponse.next_page_token]. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSecretsResponse(proto.Message): + r"""Response message for + [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets]. + + Attributes: + secrets (Sequence[~.resources.Secret]): + The list of [Secrets][google.cloud.secrets.v1beta1.Secret] + sorted in reverse by create_time (newest first). + next_page_token (str): + A token to retrieve the next page of results. Pass this + value in + [ListSecretsRequest.page_token][google.cloud.secrets.v1beta1.ListSecretsRequest.page_token] + to retrieve the next page. + total_size (int): + The total number of + [Secrets][google.cloud.secrets.v1beta1.Secret]. + """ + + @property + def raw_page(self): + return self + + secrets = proto.RepeatedField(proto.MESSAGE, number=1, message=resources.Secret,) + + next_page_token = proto.Field(proto.STRING, number=2) + + total_size = proto.Field(proto.INT32, number=3) + + +class CreateSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.CreateSecret][google.cloud.secrets.v1beta1.SecretManagerService.CreateSecret]. + + Attributes: + parent (str): + Required. The resource name of the project to associate with + the [Secret][google.cloud.secrets.v1beta1.Secret], in the + format ``projects/*``. + secret_id (str): + Required. This must be unique within the project. + + A secret ID is a string with a maximum length of 255 + characters and can contain uppercase and lowercase letters, + numerals, and the hyphen (``-``) and underscore (``_``) + characters. + secret (~.resources.Secret): + Required. A [Secret][google.cloud.secrets.v1beta1.Secret] + with initial field values. + """ + + parent = proto.Field(proto.STRING, number=1) + + secret_id = proto.Field(proto.STRING, number=2) + + secret = proto.Field(proto.MESSAGE, number=3, message=resources.Secret,) + + +class AddSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.AddSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AddSecretVersion]. + + Attributes: + parent (str): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] to associate + with the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*``. + payload (~.resources.SecretPayload): + Required. The secret payload of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + """ + + parent = proto.Field(proto.STRING, number=1) + + payload = proto.Field(proto.MESSAGE, number=2, message=resources.SecretPayload,) + + +class GetSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.GetSecret][google.cloud.secrets.v1beta1.SecretManagerService.GetSecret]. + + Attributes: + name (str): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret], in the format + ``projects/*/secrets/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListSecretVersionsRequest(proto.Message): + r"""Request message for + [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. + + Attributes: + parent (str): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] associated + with the + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + to list, in the format ``projects/*/secrets/*``. + page_size (int): + Optional. The maximum number of results to be + returned in a single page. If set to 0, the + server decides the number of results to return. + If the number is greater than 25000, it is + capped at 25000. + page_token (str): + Optional. Pagination token, returned earlier via + ListSecretVersionsResponse.next_page_token][]. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListSecretVersionsResponse(proto.Message): + r"""Response message for + [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions]. + + Attributes: + versions (Sequence[~.resources.SecretVersion]): + The list of + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] + sorted in reverse by create_time (newest first). + next_page_token (str): + A token to retrieve the next page of results. Pass this + value in + [ListSecretVersionsRequest.page_token][google.cloud.secrets.v1beta1.ListSecretVersionsRequest.page_token] + to retrieve the next page. + total_size (int): + The total number of + [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, number=1, message=resources.SecretVersion, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + total_size = proto.Field(proto.INT32, number=3) + + +class GetSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.GetSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.GetSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + ``projects/*/secrets/*/versions/latest`` is an alias to the + ``latest`` + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.UpdateSecret][google.cloud.secrets.v1beta1.SecretManagerService.UpdateSecret]. + + Attributes: + secret (~.resources.Secret): + Required. [Secret][google.cloud.secrets.v1beta1.Secret] with + updated field values. + update_mask (~.field_mask.FieldMask): + Required. Specifies the fields to be updated. + """ + + secret = proto.Field(proto.MESSAGE, number=1, message=resources.Secret,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class AccessSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class AccessSecretVersionResponse(proto.Message): + r"""Response message for + [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion]. + + Attributes: + name (str): + The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + in the format ``projects/*/secrets/*/versions/*``. + payload (~.resources.SecretPayload): + Secret payload + """ + + name = proto.Field(proto.STRING, number=1) + + payload = proto.Field(proto.MESSAGE, number=2, message=resources.SecretPayload,) + + +class DeleteSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.DeleteSecret][google.cloud.secrets.v1beta1.SecretManagerService.DeleteSecret]. + + Attributes: + name (str): + Required. The resource name of the + [Secret][google.cloud.secrets.v1beta1.Secret] to delete in + the format ``projects/*/secrets/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DisableSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.DisableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DisableSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to disable in the format + ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class EnableSecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.EnableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.EnableSecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to enable in the format ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DestroySecretVersionRequest(proto.Message): + r"""Request message for + [SecretManagerService.DestroySecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DestroySecretVersion]. + + Attributes: + name (str): + Required. The resource name of the + [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] + to destroy in the format + ``projects/*/secrets/*/versions/*``. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index 39c3dc0..e906161 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -139,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=75") + session.run("coverage", "report", "--show-missing", "--fail-under=99") session.run("coverage", "erase") diff --git a/samples/snippets/access_secret_version.py b/samples/snippets/access_secret_version.py index c620ea3..a8e2837 100644 --- a/samples/snippets/access_secret_version.py +++ b/samples/snippets/access_secret_version.py @@ -33,29 +33,29 @@ def access_secret_version(project_id, secret_id, version_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret version. - name = client.secret_version_path(project_id, secret_id, version_id) + name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" # Access the secret version. - response = client.access_secret_version(name) + response = client.access_secret_version(request={"name": name}) # Print the secret payload. # # WARNING: Do not print the secret in a production environment - this # snippet is showing how to access the secret material. - payload = response.payload.data.decode('UTF-8') - print('Plaintext: {}'.format(payload)) -# [END secretmanager_access_secret_version] + payload = response.payload.data.decode("UTF-8") + print("Plaintext: {}".format(payload)) + # [END secretmanager_access_secret_version] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret to access') - parser.add_argument('version_id', help='version to access') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret to access") + parser.add_argument("version_id", help="version to access") args = parser.parse_args() access_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/samples/snippets/add_secret_version.py b/samples/snippets/add_secret_version.py index 51be871..442b12e 100644 --- a/samples/snippets/add_secret_version.py +++ b/samples/snippets/add_secret_version.py @@ -37,25 +37,27 @@ def add_secret_version(project_id, secret_id, payload): # Convert the string payload into a bytes. This step can be omitted if you # pass in bytes instead of a str for the payload argument. - payload = payload.encode('UTF-8') + payload = payload.encode("UTF-8") # Add the secret version. - response = client.add_secret_version(parent, {'data': payload}) + response = client.add_secret_version( + request={"parent": parent, "payload": {"data": payload}} + ) # Print the new secret version name. - print('Added secret version: {}'.format(response.name)) -# [END secretmanager_add_secret_version] + print("Added secret version: {}".format(response.name)) + # [END secretmanager_add_secret_version] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret in which to add') - parser.add_argument('payload', help='secret material payload') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret in which to add") + parser.add_argument("payload", help="secret material payload") args = parser.parse_args() add_secret_version(args.project_id, args.secret_id, args.payload) diff --git a/samples/snippets/create_secret.py b/samples/snippets/create_secret.py index 23d9347..67a9839 100644 --- a/samples/snippets/create_secret.py +++ b/samples/snippets/create_secret.py @@ -34,28 +34,30 @@ def create_secret(project_id, secret_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the parent project. - parent = client.project_path(project_id) + parent = f"projects/{project_id}" # Create the secret. - response = client.create_secret(parent, secret_id, { - 'replication': { - 'automatic': {}, - }, - }) + response = client.create_secret( + request={ + "parent": parent, + "secret_id": secret_id, + "secret": {"replication": {"automatic": {}}}, + } + ) # Print the new secret name. - print('Created secret: {}'.format(response.name)) -# [END secretmanager_create_secret] + print("Created secret: {}".format(response.name)) + # [END secretmanager_create_secret] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret to create') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret to create") args = parser.parse_args() create_secret(args.project_id, args.secret_id) diff --git a/samples/snippets/delete_secret.py b/samples/snippets/delete_secret.py index 3ee5a2b..ad58236 100644 --- a/samples/snippets/delete_secret.py +++ b/samples/snippets/delete_secret.py @@ -35,16 +35,18 @@ def delete_secret(project_id, secret_id): name = client.secret_path(project_id, secret_id) # Delete the secret. - client.delete_secret(name) + client.delete_secret(request={"name": name}) + + # [END secretmanager_delete_secret] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret to delete') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret to delete") args = parser.parse_args() delete_secret(args.project_id, args.secret_id) diff --git a/samples/snippets/destroy_secret_version.py b/samples/snippets/destroy_secret_version.py index 1d03318..3a812a0 100644 --- a/samples/snippets/destroy_secret_version.py +++ b/samples/snippets/destroy_secret_version.py @@ -33,24 +33,24 @@ def destroy_secret_version(project_id, secret_id, version_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret version - name = client.secret_version_path(project_id, secret_id, version_id) + name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" # Destroy the secret version. - response = client.destroy_secret_version(name) + response = client.destroy_secret_version(request={"name": name}) - print('Destroyed secret version: {}'.format(response.name)) -# [END secretmanager_destroy_secret_version] + print("Destroyed secret version: {}".format(response.name)) + # [END secretmanager_destroy_secret_version] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret from which to act') - parser.add_argument('version_id', help='id of the version to destroy') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret from which to act") + parser.add_argument("version_id", help="id of the version to destroy") args = parser.parse_args() destroy_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/samples/snippets/disable_secret_version.py b/samples/snippets/disable_secret_version.py index a88f1a7..8d7a115 100644 --- a/samples/snippets/disable_secret_version.py +++ b/samples/snippets/disable_secret_version.py @@ -33,24 +33,24 @@ def disable_secret_version(project_id, secret_id, version_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret version - name = client.secret_version_path(project_id, secret_id, version_id) + name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" # Disable the secret version. - response = client.disable_secret_version(name) + response = client.disable_secret_version(request={"name": name}) - print('Disabled secret version: {}'.format(response.name)) -# [END secretmanager_disable_secret_version] + print("Disabled secret version: {}".format(response.name)) + # [END secretmanager_disable_secret_version] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret from which to act') - parser.add_argument('version_id', help='id of the version to disable') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret from which to act") + parser.add_argument("version_id", help="id of the version to disable") args = parser.parse_args() disable_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/samples/snippets/enable_secret_version.py b/samples/snippets/enable_secret_version.py index c14e2bb..c465f3f 100644 --- a/samples/snippets/enable_secret_version.py +++ b/samples/snippets/enable_secret_version.py @@ -33,24 +33,24 @@ def enable_secret_version(project_id, secret_id, version_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret version - name = client.secret_version_path(project_id, secret_id, version_id) + name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" # Disable the secret version. - response = client.enable_secret_version(name) + response = client.enable_secret_version(request={"name": name}) - print('Enabled secret version: {}'.format(response.name)) -# [END secretmanager_enable_secret_version] + print("Enabled secret version: {}".format(response.name)) + # [END secretmanager_enable_secret_version] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret from which to act') - parser.add_argument('version_id', help='id of the version to enable') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret from which to act") + parser.add_argument("version_id", help="id of the version to enable") args = parser.parse_args() enable_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/samples/snippets/get_secret.py b/samples/snippets/get_secret.py index 5eea886..39b60aa 100644 --- a/samples/snippets/get_secret.py +++ b/samples/snippets/get_secret.py @@ -36,30 +36,29 @@ def get_secret(project_id, secret_id): name = client.secret_path(project_id, secret_id) # Get the secret. - response = client.get_secret(name) + response = client.get_secret(request={"name": name}) # Get the replication policy. - if response.replication.automatic: - replication = 'AUTOMATIC' - elif response.replication.user_managed: - replication = 'MANAGED' + if "automatic" in response.replication: + replication = "AUTOMATIC" + elif "user_managed" in response.replication: + replication = "MANAGED" else: - raise 'Unknown replication {}'.format(response.replication) + raise "Unknown replication {}".format(response.replication) # Print data about the secret. - print('Got secret {} with replication policy {}'.format( - response.name, replication)) -# [END secretmanager_get_secret] + print("Got secret {} with replication policy {}".format(response.name, replication)) + # [END secretmanager_get_secret] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret to get') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret to get") args = parser.parse_args() get_secret(args.project_id, args.secret_id) diff --git a/samples/snippets/get_secret_version.py b/samples/snippets/get_secret_version.py index 7ddb8a5..e38b4cc 100644 --- a/samples/snippets/get_secret_version.py +++ b/samples/snippets/get_secret_version.py @@ -34,26 +34,26 @@ def get_secret_version(project_id, secret_id, version_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret version. - name = client.secret_version_path(project_id, secret_id, version_id) + name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" # Get the secret version. - response = client.get_secret_version(name) + response = client.get_secret_version(request={"name": name}) # Print information about the secret version. - state = response.State.Name(response.state) - print('Got secret version {} with state {}'.format(response.name, state)) -# [END secretmanager_get_secret_version] + state = response.state.name + print("Got secret version {} with state {}".format(response.name, state)) + # [END secretmanager_get_secret_version] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret from which to act') - parser.add_argument('version_id', help='id of the version to get') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret from which to act") + parser.add_argument("version_id", help="id of the version to get") args = parser.parse_args() get_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/samples/snippets/iam_grant_access.py b/samples/snippets/iam_grant_access.py index 3c3a7e7..ce2bb5f 100644 --- a/samples/snippets/iam_grant_access.py +++ b/samples/snippets/iam_grant_access.py @@ -35,30 +35,28 @@ def iam_grant_access(project_id, secret_id, member): name = client.secret_path(project_id, secret_id) # Get the current IAM policy. - policy = client.get_iam_policy(name) + policy = client.get_iam_policy(request={"resource": name}) # Add the given member with access permissions. - policy.bindings.add( - role='roles/secretmanager.secretAccessor', - members=[member]) + policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member]) # Update the IAM Policy. - new_policy = client.set_iam_policy(name, policy) + new_policy = client.set_iam_policy(request={"resource": name, "policy": policy}) # Print data about the secret. - print('Updated IAM policy on {}'.format(secret_id)) -# [END secretmanager_iam_grant_access] + print("Updated IAM policy on {}".format(secret_id)) + # [END secretmanager_iam_grant_access] return new_policy -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret to get') - parser.add_argument('member', help='member to grant access') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret to get") + parser.add_argument("member", help="member to grant access") args = parser.parse_args() iam_grant_access(args.project_id, args.secret_id, args.member) diff --git a/samples/snippets/iam_revoke_access.py b/samples/snippets/iam_revoke_access.py index 385a52a..648234d 100644 --- a/samples/snippets/iam_revoke_access.py +++ b/samples/snippets/iam_revoke_access.py @@ -35,31 +35,31 @@ def iam_revoke_access(project_id, secret_id, member): name = client.secret_path(project_id, secret_id) # Get the current IAM policy. - policy = client.get_iam_policy(name) + policy = client.get_iam_policy(request={"resource": name}) # Remove the given member's access permissions. - accessRole = 'roles/secretmanager.secretAccessor' + accessRole = "roles/secretmanager.secretAccessor" for b in list(policy.bindings): if b.role == accessRole and member in b.members: b.members.remove(member) # Update the IAM Policy. - new_policy = client.set_iam_policy(name, policy) + new_policy = client.set_iam_policy(request={"resource": name, "policy": policy}) # Print data about the secret. - print('Updated IAM policy on {}'.format(secret_id)) -# [END secretmanager_iam_revoke_access] + print("Updated IAM policy on {}".format(secret_id)) + # [END secretmanager_iam_revoke_access] return new_policy -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret to get') - parser.add_argument('member', help='member to revoke access') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret to get") + parser.add_argument("member", help="member to revoke access") args = parser.parse_args() iam_revoke_access(args.project_id, args.secret_id, args.member) diff --git a/samples/snippets/list_secret_versions.py b/samples/snippets/list_secret_versions.py index 2ff4434..c60ac02 100644 --- a/samples/snippets/list_secret_versions.py +++ b/samples/snippets/list_secret_versions.py @@ -36,17 +36,19 @@ def list_secret_versions(project_id, secret_id): parent = client.secret_path(project_id, secret_id) # List all secret versions. - for version in client.list_secret_versions(parent): - print('Found secret version: {}'.format(version.name)) + for version in client.list_secret_versions(request={"parent": parent}): + print("Found secret version: {}".format(version.name)) + + # [END secretmanager_list_secret_versions] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('secret_id', help='id of the secret in which to list') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("secret_id", help="id of the secret in which to list") args = parser.parse_args() list_secret_versions(args.project_id, args.secret_id) diff --git a/samples/snippets/list_secrets.py b/samples/snippets/list_secrets.py index 0d0e798..b07a0b0 100644 --- a/samples/snippets/list_secrets.py +++ b/samples/snippets/list_secrets.py @@ -32,19 +32,21 @@ def list_secrets(project_id): client = secretmanager.SecretManagerServiceClient() # Build the resource name of the parent project. - parent = client.project_path(project_id) + parent = f"projects/{project_id}" # List all secrets. - for secret in client.list_secrets(parent): - print('Found secret: {}'.format(secret.name)) + for secret in client.list_secrets(request={"parent": parent}): + print("Found secret: {}".format(secret.name)) + + # [END secretmanager_list_secrets] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") args = parser.parse_args() list_secrets(args.project_id) diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 68b1b04..9386020 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -23,10 +23,10 @@ def quickstart(_project_id=None, _secret_id=None): from google.cloud import secretmanager # GCP project in which to store secrets in Secret Manager. - project_id = 'YOUR_PROJECT_ID' + project_id = "YOUR_PROJECT_ID" # ID of the secret to create. - secret_id = 'YOUR_SECRET_ID' + secret_id = "YOUR_SECRET_ID" # [END secretmanager_quickstart] project_id = _project_id @@ -36,29 +36,33 @@ def quickstart(_project_id=None, _secret_id=None): client = secretmanager.SecretManagerServiceClient() # Build the parent name from the project. - parent = client.project_path(project_id) + parent = f"projects/{project_id}" # Create the parent secret. - secret = client.create_secret(parent, secret_id, { - 'replication': { - 'automatic': {}, - }, - }) + secret = client.create_secret( + request={ + "parent": parent, + "secret_id": secret_id, + "secret": {"replication": {"automatic": {}}}, + } + ) # Add the secret version. - version = client.add_secret_version(secret.name, {'data': b'hello world!'}) + version = client.add_secret_version( + request={"parent": secret.name, "payload": {"data": b"hello world!"}} + ) # Access the secret version. - response = client.access_secret_version(version.name) + response = client.access_secret_version(request={"name": version.name}) # Print the secret payload. # # WARNING: Do not print the secret in a production environment - this # snippet is showing how to access the secret material. - payload = response.payload.data.decode('UTF-8') - print('Plaintext: {}'.format(payload)) + payload = response.payload.data.decode("UTF-8") + print("Plaintext: {}".format(payload)) # [END secretmanager_quickstart] -if __name__ == '__main__': +if __name__ == "__main__": quickstart() diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index da667b1..9da3902 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-secret-manager==1.0.0 +google-cloud-secret-manager==1.0.0 \ No newline at end of file diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 65f93be..d48d306 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -42,31 +42,33 @@ def client(): @pytest.fixture() def project_id(): - return os.environ['GOOGLE_CLOUD_PROJECT'] + return os.environ["GOOGLE_CLOUD_PROJECT"] @pytest.fixture() def iam_user(): - return 'serviceAccount:' + os.environ['GCLOUD_SECRETS_SERVICE_ACCOUNT'] + return "serviceAccount:" + os.environ["GCLOUD_SECRETS_SERVICE_ACCOUNT"] @pytest.fixture() def secret(client, project_id): - parent = client.project_path(project_id) - secret_id = 'python-secret-{}'.format(uuid.uuid4()) - - print('creating secret {}'.format(secret_id)) - secret = client.create_secret(parent, secret_id, { - 'replication': { - 'automatic': {}, - }, - }) + parent = f"projects/{project_id}" + secret_id = "python-secret-{}".format(uuid.uuid4()) + + print("creating secret {}".format(secret_id)) + secret = client.create_secret( + request={ + "parent": parent, + "secret_id": secret_id, + "secret": {"replication": {"automatic": {}}}, + } + ) yield project_id, secret_id - print('deleting secret {}'.format(secret_id)) + print("deleting secret {}".format(secret_id)) try: - client.delete_secret(secret.name) + client.delete_secret(request={"name": secret.name}) except exceptions.NotFound: # Secret was already deleted, probably in the test pass @@ -79,49 +81,51 @@ def secret(client, project_id): def secret_version(client, secret): project_id, secret_id = secret - print('adding secret version to {}'.format(secret_id)) + print("adding secret version to {}".format(secret_id)) parent = client.secret_path(project_id, secret_id) - payload = 'hello world!'.encode('UTF-8') - version = client.add_secret_version(parent, {'data': payload}) + payload = "hello world!".encode("UTF-8") + version = client.add_secret_version( + request={"parent": parent, "payload": {"data": payload}} + ) - yield project_id, secret_id, version.name.rsplit('/', 1)[-1] + yield project_id, secret_id, version.name.rsplit("/", 1)[-1] another_secret_version = secret_version def test_quickstart(project_id): - secret_id = 'python-secret-{}'.format(uuid.uuid4()) + secret_id = "python-secret-{}".format(uuid.uuid4()) quickstart(project_id, secret_id) def test_access_secret_version(secret_version): project_id, secret_id, version_id = secret_version version = access_secret_version(project_id, secret_id, version_id) - assert version.payload.data == b'hello world!' + assert version.payload.data == b"hello world!" def test_add_secret_version(secret): project_id, secret_id = secret - payload = 'test123' + payload = "test123" version = add_secret_version(project_id, secret_id, payload) assert secret_id in version.name def test_create_secret(client, project_id): - secret_id = 'python-secret-{}'.format(uuid.uuid4()) + secret_id = "python-secret-{}".format(uuid.uuid4()) secret = create_secret(project_id, secret_id) assert secret_id in secret.name - client.delete_secret(secret.name) + client.delete_secret(request={"name": secret.name}) def test_delete_secret(client, secret): project_id, secret_id = secret delete_secret(project_id, secret_id) with pytest.raises(exceptions.NotFound): - print('{}'.format(client)) - name = client.secret_version_path(project_id, secret_id, 'latest') - client.access_secret_version(name) + print("{}".format(client)) + name = f"projects/{project_id}/secrets/{secret_id}/versions/latest" + client.access_secret_version(request={"name": name}) def test_destroy_secret_version(client, secret_version): @@ -133,10 +137,10 @@ def test_destroy_secret_version(client, secret_version): def test_enable_disable_secret_version(client, secret_version): project_id, secret_id, version_id = secret_version version = disable_secret_version(project_id, secret_id, version_id) - assert version.state == secretmanager.enums.SecretVersion.State.DISABLED + assert version.state == secretmanager.SecretVersion.State.DISABLED version = enable_secret_version(project_id, secret_id, version_id) - assert version.state == secretmanager.enums.SecretVersion.State.ENABLED + assert version.state == secretmanager.SecretVersion.State.ENABLED def test_get_secret_version(client, secret_version): @@ -188,4 +192,4 @@ def test_list_secrets(capsys, secret, another_secret): def test_update_secret(secret): project_id, secret_id = secret secret = update_secret(project_id, secret_id) - assert secret.labels['secretmanager'] == 'rocks' + assert secret.labels["secretmanager"] == "rocks" diff --git a/samples/snippets/update_secret.py b/samples/snippets/update_secret.py index 8c97d91..1dd8ec7 100644 --- a/samples/snippets/update_secret.py +++ b/samples/snippets/update_secret.py @@ -32,23 +32,25 @@ def update_secret(project_id, secret_id): name = client.secret_path(project_id, secret_id) # Update the secret. - secret = {'name': name, 'labels': {'secretmanager': 'rocks'}} - update_mask = {'paths': ['labels']} - response = client.update_secret(secret, update_mask) + secret = {"name": name, "labels": {"secretmanager": "rocks"}} + update_mask = {"paths": ["labels"]} + response = client.update_secret( + request={"secret": secret, "update_mask": update_mask} + ) # Print the new secret name. - print('Updated secret: {}'.format(response.name)) + print("Updated secret: {}".format(response.name)) # [END secretmanager_update_secret] return response -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='id of the GCP project') - parser.add_argument('--secret-id', required=True) + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="id of the GCP project") + parser.add_argument("--secret-id", required=True) args = parser.parse_args() update_secret(args.project_id, args.secret_id) diff --git a/scripts/fixup_secretmanager_v1_keywords.py b/scripts/fixup_secretmanager_v1_keywords.py new file mode 100644 index 0000000..afad384 --- /dev/null +++ b/scripts/fixup_secretmanager_v1_keywords.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class secretmanagerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'access_secret_version': ('name', ), + 'add_secret_version': ('parent', 'payload', ), + 'create_secret': ('parent', 'secret_id', 'secret', ), + 'delete_secret': ('name', ), + 'destroy_secret_version': ('name', ), + 'disable_secret_version': ('name', ), + 'enable_secret_version': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_secret': ('name', ), + 'get_secret_version': ('name', ), + 'list_secrets': ('parent', 'page_size', 'page_token', ), + 'list_secret_versions': ('parent', 'page_size', 'page_token', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_secret': ('secret', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=secretmanagerCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the secretmanager client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_secretmanager_v1beta1_keywords.py b/scripts/fixup_secretmanager_v1beta1_keywords.py new file mode 100644 index 0000000..afad384 --- /dev/null +++ b/scripts/fixup_secretmanager_v1beta1_keywords.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class secretmanagerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'access_secret_version': ('name', ), + 'add_secret_version': ('parent', 'payload', ), + 'create_secret': ('parent', 'secret_id', 'secret', ), + 'delete_secret': ('name', ), + 'destroy_secret_version': ('name', ), + 'disable_secret_version': ('name', ), + 'enable_secret_version': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_secret': ('name', ), + 'get_secret_version': ('name', ), + 'list_secrets': ('parent', 'page_size', 'page_token', ), + 'list_secret_versions': ('parent', 'page_size', 'page_token', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_secret': ('secret', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=secretmanagerCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the secretmanager client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index f2af037..481eadd 100644 --- a/setup.py +++ b/setup.py @@ -25,9 +25,10 @@ version = "1.0.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", - 'enum34; python_version < "3.4"', + "proto-plus >= 1.4.0", + "libcst >= 0.2.5", ] package_root = os.path.abspath(os.path.dirname(__file__)) @@ -37,7 +38,9 @@ readme = readme_file.read() packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] namespaces = ["google"] @@ -59,9 +62,9 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -69,7 +72,11 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=[ + "scripts/fixup_secretmanager_v1_keywords.py", + "scripts/fixup_secretmanager_v1beta1_keywords.py", + ], include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index 14039dd..55eecb8 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-secret-manager.git", - "sha": "8e2ef9921c7af1c8bd3620c728413470c790a02f" + "sha": "538071bbe633d02303572a56cf5894abff141201" } }, { diff --git a/synth.py b/synth.py index 089cbd4..136a5d6 100644 --- a/synth.py +++ b/synth.py @@ -21,6 +21,7 @@ gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() +excludes = ["README.rst", "setup.py", "nox*.py", "docs/index.rst"] # ---------------------------------------------------------------------------- # Generate secret manager GAPIC layer @@ -38,68 +39,17 @@ version=version, bazel_target=bazel_target, ) - - s.move( - library, - excludes=[ - f"google/cloud/secrets_{version}/proto", - "nox.py", - "setup.py", - "README.rst", - "docs/index.rst", - ], - ) - - # protos are copied to the wrong location by default, so move separately - s.move( - library / f"google/cloud/secrets_{version}/proto", - f"google/cloud/secretmanager_{version}/proto", - ) - - # correct proto import parth - s.replace( - "google/cloud/**/proto/*.py", - rf"from google\.cloud\.secrets_{version}\.proto", - f"from google.cloud.secretmanager_{version}.proto", - ) - -# fix import path for iam -s.replace( - "google/**/gapic/transports/*_grpc_transport.py", - "from google.iam.v1 import iam_policy_pb2 ", - "from google.iam.v1 import iam_policy_pb2_grpc as iam_policy_pb2", -) - -# correct license headers -python.fix_pb2_headers() -python.fix_pb2_grpc_headers() - -# Fix package name (v1beta1) -s.replace( - ["docs/conf.py", "google/**/*.py", "README.rst", "setup.py"], - "google-cloud-secretmanager", - "google-cloud-secret-manager", -) - -# Fix package name (v1) -s.replace( - ["docs/conf.py", "google/**/*.py", "README.rst", "setup.py"], - "google-cloud-secrets", - "google-cloud-secret-manager", -) - -# fix links in README -s.replace( - "README.rst", - "https://cloud\.google\.com/secrets", - "https://cloud.google.com/secret-manager", -) + s.copy(library, excludes=excludes) # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=75, samples=True) -s.move(templated_files) +templated_files = common.py_library( + samples=True, # set to True only if there are samples + microgenerator=True, + cov_level=99, +) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file # ---------------------------------------------------------------------------- # Samples templates diff --git a/tests/unit/gapic/secretmanager_v1/__init__.py b/tests/unit/gapic/secretmanager_v1/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/unit/gapic/secretmanager_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py b/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py new file mode 100644 index 0000000..653a7e0 --- /dev/null +++ b/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py @@ -0,0 +1,3983 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.secretmanager_v1.services.secret_manager_service import ( + SecretManagerServiceAsyncClient, +) +from google.cloud.secretmanager_v1.services.secret_manager_service import ( + SecretManagerServiceClient, +) +from google.cloud.secretmanager_v1.services.secret_manager_service import pagers +from google.cloud.secretmanager_v1.services.secret_manager_service import transports +from google.cloud.secretmanager_v1.types import resources +from google.cloud.secretmanager_v1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SecretManagerServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [SecretManagerServiceClient, SecretManagerServiceAsyncClient] +) +def test_secret_manager_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "secretmanager.googleapis.com:443" + + +def test_secret_manager_service_client_get_transport_class(): + transport = SecretManagerServiceClient.get_transport_class() + assert transport == transports.SecretManagerServiceGrpcTransport + + transport = SecretManagerServiceClient.get_transport_class("grpc") + assert transport == transports.SecretManagerServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + SecretManagerServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceClient), +) +@mock.patch.object( + SecretManagerServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceAsyncClient), +) +def test_secret_manager_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecretManagerServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecretManagerServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + "true", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + "false", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + SecretManagerServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceClient), +) +@mock.patch.object( + SecretManagerServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_secret_manager_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_secret_manager_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_secret_manager_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_secret_manager_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.secretmanager_v1.services.secret_manager_service.transports.SecretManagerServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SecretManagerServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_secrets(transport: str = "grpc", request_type=service.ListSecretsRequest): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + + response = client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListSecretsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretsPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secrets_from_dict(): + test_list_secrets(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_secrets_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.ListSecretsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + ) + + response = await client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secrets_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + call.return_value = service.ListSecretsResponse() + + client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_secrets_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretsResponse() + ) + + await client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_secrets_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_secrets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_secrets_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_secrets( + service.ListSecretsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_secrets_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_secrets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_secrets_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_secrets( + service.ListSecretsRequest(), parent="parent_value", + ) + + +def test_list_secrets_pager(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_secrets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.Secret) for i in results) + + +def test_list_secrets_pages(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + pages = list(client.list_secrets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_secrets_async_pager(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + async_pager = await client.list_secrets(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Secret) for i in responses) + + +@pytest.mark.asyncio +async def test_list_secrets_async_pages(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_secrets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_secret( + transport: str = "grpc", request_type=service.CreateSecretRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret(name="name_value",) + + response = client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.CreateSecretRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_create_secret_from_dict(): + test_create_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.CreateSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Secret(name="name_value",) + ) + + response = await client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_create_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecretRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_secret), "__call__") as call: + call.return_value = resources.Secret() + + client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecretRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + + await client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_secret( + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].secret_id == "secret_id_value" + + assert args[0].secret == resources.Secret(name="name_value") + + +def test_create_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_secret( + service.CreateSecretRequest(), + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_secret( + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].secret_id == "secret_id_value" + + assert args[0].secret == resources.Secret(name="name_value") + + +@pytest.mark.asyncio +async def test_create_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_secret( + service.CreateSecretRequest(), + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + +def test_add_secret_version( + transport: str = "grpc", request_type=service.AddSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.AddSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_add_secret_version_from_dict(): + test_add_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_add_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.AddSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_add_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AddSecretVersionRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AddSecretVersionRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_add_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_secret_version( + parent="parent_value", payload=resources.SecretPayload(data=b"data_blob"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].payload == resources.SecretPayload(data=b"data_blob") + + +def test_add_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_secret_version( + service.AddSecretVersionRequest(), + parent="parent_value", + payload=resources.SecretPayload(data=b"data_blob"), + ) + + +@pytest.mark.asyncio +async def test_add_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_secret_version( + parent="parent_value", payload=resources.SecretPayload(data=b"data_blob"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].payload == resources.SecretPayload(data=b"data_blob") + + +@pytest.mark.asyncio +async def test_add_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_secret_version( + service.AddSecretVersionRequest(), + parent="parent_value", + payload=resources.SecretPayload(data=b"data_blob"), + ) + + +def test_get_secret(transport: str = "grpc", request_type=service.GetSecretRequest): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret(name="name_value",) + + response = client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetSecretRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_get_secret_from_dict(): + test_get_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.GetSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Secret(name="name_value",) + ) + + response = await client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_get_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_secret), "__call__") as call: + call.return_value = resources.Secret() + + client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + + await client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_secret( + service.GetSecretRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_secret( + service.GetSecretRequest(), name="name_value", + ) + + +def test_update_secret( + transport: str = "grpc", request_type=service.UpdateSecretRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret(name="name_value",) + + response = client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.UpdateSecretRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_update_secret_from_dict(): + test_update_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.UpdateSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Secret(name="name_value",) + ) + + response = await client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_update_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateSecretRequest() + request.secret.name = "secret.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_secret), "__call__") as call: + call.return_value = resources.Secret() + + client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "secret.name=secret.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateSecretRequest() + request.secret.name = "secret.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + + await client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "secret.name=secret.name/value",) in kw["metadata"] + + +def test_update_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_secret( + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].secret == resources.Secret(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_secret( + service.UpdateSecretRequest(), + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_secret( + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].secret == resources.Secret(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_secret( + service.UpdateSecretRequest(), + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_secret( + transport: str = "grpc", request_type=service.DeleteSecretRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DeleteSecretRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_secret_from_dict(): + test_delete_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.DeleteSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_secret), "__call__") as call: + call.return_value = None + + client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_secret( + service.DeleteSecretRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_secret( + service.DeleteSecretRequest(), name="name_value", + ) + + +def test_list_secret_versions( + transport: str = "grpc", request_type=service.ListSecretVersionsRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretVersionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + + response = client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListSecretVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretVersionsPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secret_versions_from_dict(): + test_list_secret_versions(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_secret_versions_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.ListSecretVersionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretVersionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + ) + + response = await client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretVersionsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secret_versions_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretVersionsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + call.return_value = service.ListSecretVersionsResponse() + + client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_secret_versions_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretVersionsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretVersionsResponse() + ) + + await client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_secret_versions_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretVersionsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_secret_versions(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_secret_versions_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_secret_versions( + service.ListSecretVersionsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_secret_versions_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_secret_versions(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_secret_versions_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_secret_versions( + service.ListSecretVersionsRequest(), parent="parent_value", + ) + + +def test_list_secret_versions_pager(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_secret_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.SecretVersion) for i in results) + + +def test_list_secret_versions_pages(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + pages = list(client.list_secret_versions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_secret_versions_async_pager(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + async_pager = await client.list_secret_versions(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SecretVersion) for i in responses) + + +@pytest.mark.asyncio +async def test_list_secret_versions_async_pages(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_secret_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_secret_version( + transport: str = "grpc", request_type=service.GetSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_get_secret_version_from_dict(): + test_get_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.GetSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_get_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_secret_version( + service.GetSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_secret_version( + service.GetSecretVersionRequest(), name="name_value", + ) + + +def test_access_secret_version( + transport: str = "grpc", request_type=service.AccessSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AccessSecretVersionResponse(name="name_value",) + + response = client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.AccessSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AccessSecretVersionResponse) + + assert response.name == "name_value" + + +def test_access_secret_version_from_dict(): + test_access_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_access_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.AccessSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AccessSecretVersionResponse(name="name_value",) + ) + + response = await client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AccessSecretVersionResponse) + + assert response.name == "name_value" + + +def test_access_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AccessSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.access_secret_version), "__call__" + ) as call: + call.return_value = service.AccessSecretVersionResponse() + + client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_access_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AccessSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.access_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AccessSecretVersionResponse() + ) + + await client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_access_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AccessSecretVersionResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.access_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_access_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.access_secret_version( + service.AccessSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_access_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AccessSecretVersionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AccessSecretVersionResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.access_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_access_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.access_secret_version( + service.AccessSecretVersionRequest(), name="name_value", + ) + + +def test_disable_secret_version( + transport: str = "grpc", request_type=service.DisableSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DisableSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_disable_secret_version_from_dict(): + test_disable_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_disable_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.DisableSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_disable_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DisableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.disable_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_disable_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DisableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.disable_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_disable_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.disable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_disable_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.disable_secret_version( + service.DisableSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_disable_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.disable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_disable_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.disable_secret_version( + service.DisableSecretVersionRequest(), name="name_value", + ) + + +def test_enable_secret_version( + transport: str = "grpc", request_type=service.EnableSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.EnableSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_enable_secret_version_from_dict(): + test_enable_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_enable_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.EnableSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_enable_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EnableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.enable_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_enable_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EnableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.enable_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_enable_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.enable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_enable_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enable_secret_version( + service.EnableSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_enable_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.enable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_enable_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.enable_secret_version( + service.EnableSecretVersionRequest(), name="name_value", + ) + + +def test_destroy_secret_version( + transport: str = "grpc", request_type=service.DestroySecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DestroySecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_destroy_secret_version_from_dict(): + test_destroy_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_destroy_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.DestroySecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_destroy_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroySecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.destroy_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_destroy_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroySecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.destroy_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_destroy_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.destroy_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_destroy_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.destroy_secret_version( + service.DestroySecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_destroy_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.destroy_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_destroy_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.destroy_secret_version( + service.DestroySecretVersionRequest(), name="name_value", + ) + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + call.return_value = policy.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy( + transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + call.return_value = policy.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecretManagerServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecretManagerServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = SecretManagerServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecretManagerServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecretManagerServiceGrpcTransport, + transports.SecretManagerServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.SecretManagerServiceGrpcTransport,) + + +def test_secret_manager_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.SecretManagerServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_secret_manager_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.secretmanager_v1.services.secret_manager_service.transports.SecretManagerServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SecretManagerServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_secrets", + "create_secret", + "add_secret_version", + "get_secret", + "update_secret", + "delete_secret", + "list_secret_versions", + "get_secret_version", + "access_secret_version", + "disable_secret_version", + "enable_secret_version", + "destroy_secret_version", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_secret_manager_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.secretmanager_v1.services.secret_manager_service.transports.SecretManagerServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.SecretManagerServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_secret_manager_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.secretmanager_v1.services.secret_manager_service.transports.SecretManagerServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.SecretManagerServiceTransport() + adc.assert_called_once() + + +def test_secret_manager_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SecretManagerServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_secret_manager_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SecretManagerServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_secret_manager_service_host_no_port(): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="secretmanager.googleapis.com" + ), + ) + assert client._transport._host == "secretmanager.googleapis.com:443" + + +def test_secret_manager_service_host_with_port(): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="secretmanager.googleapis.com:8000" + ), + ) + assert client._transport._host == "secretmanager.googleapis.com:8000" + + +def test_secret_manager_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.SecretManagerServiceGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_secret_manager_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.SecretManagerServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecretManagerServiceGrpcTransport, + transports.SecretManagerServiceGrpcAsyncIOTransport, + ], +) +def test_secret_manager_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecretManagerServiceGrpcTransport, + transports.SecretManagerServiceGrpcAsyncIOTransport, + ], +) +def test_secret_manager_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_secret_path(): + project = "squid" + secret = "clam" + + expected = "projects/{project}/secrets/{secret}".format( + project=project, secret=secret, + ) + actual = SecretManagerServiceClient.secret_path(project, secret) + assert expected == actual + + +def test_parse_secret_path(): + expected = { + "project": "whelk", + "secret": "octopus", + } + path = SecretManagerServiceClient.secret_path(**expected) + + # Check that the path construction is reversible. + actual = SecretManagerServiceClient.parse_secret_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.SecretManagerServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SecretManagerServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SecretManagerServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/secretmanager_v1beta1/__init__.py b/tests/unit/gapic/secretmanager_v1beta1/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/unit/gapic/secretmanager_v1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/secretmanager_v1beta1/test_secret_manager_service.py b/tests/unit/gapic/secretmanager_v1beta1/test_secret_manager_service.py new file mode 100644 index 0000000..f8ae64c --- /dev/null +++ b/tests/unit/gapic/secretmanager_v1beta1/test_secret_manager_service.py @@ -0,0 +1,3985 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.secretmanager_v1beta1.services.secret_manager_service import ( + SecretManagerServiceAsyncClient, +) +from google.cloud.secretmanager_v1beta1.services.secret_manager_service import ( + SecretManagerServiceClient, +) +from google.cloud.secretmanager_v1beta1.services.secret_manager_service import pagers +from google.cloud.secretmanager_v1beta1.services.secret_manager_service import ( + transports, +) +from google.cloud.secretmanager_v1beta1.types import resources +from google.cloud.secretmanager_v1beta1.types import service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SecretManagerServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecretManagerServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [SecretManagerServiceClient, SecretManagerServiceAsyncClient] +) +def test_secret_manager_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "secretmanager.googleapis.com:443" + + +def test_secret_manager_service_client_get_transport_class(): + transport = SecretManagerServiceClient.get_transport_class() + assert transport == transports.SecretManagerServiceGrpcTransport + + transport = SecretManagerServiceClient.get_transport_class("grpc") + assert transport == transports.SecretManagerServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + SecretManagerServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceClient), +) +@mock.patch.object( + SecretManagerServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceAsyncClient), +) +def test_secret_manager_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecretManagerServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecretManagerServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + "true", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + "false", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + SecretManagerServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceClient), +) +@mock.patch.object( + SecretManagerServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecretManagerServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_secret_manager_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_secret_manager_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecretManagerServiceClient, + transports.SecretManagerServiceGrpcTransport, + "grpc", + ), + ( + SecretManagerServiceAsyncClient, + transports.SecretManagerServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_secret_manager_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_secret_manager_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.secretmanager_v1beta1.services.secret_manager_service.transports.SecretManagerServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SecretManagerServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_secrets(transport: str = "grpc", request_type=service.ListSecretsRequest): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + + response = client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListSecretsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretsPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secrets_from_dict(): + test_list_secrets(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_secrets_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.ListSecretsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + ) + + response = await client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secrets_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + call.return_value = service.ListSecretsResponse() + + client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_secrets_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretsResponse() + ) + + await client.list_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_secrets_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_secrets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_secrets_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_secrets( + service.ListSecretsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_secrets_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_secrets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_secrets_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_secrets( + service.ListSecretsRequest(), parent="parent_value", + ) + + +def test_list_secrets_pager(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_secrets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.Secret) for i in results) + + +def test_list_secrets_pages(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_secrets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + pages = list(client.list_secrets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_secrets_async_pager(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + async_pager = await client.list_secrets(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Secret) for i in responses) + + +@pytest.mark.asyncio +async def test_list_secrets_async_pages(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secrets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(), resources.Secret(),], + next_page_token="abc", + ), + service.ListSecretsResponse(secrets=[], next_page_token="def",), + service.ListSecretsResponse( + secrets=[resources.Secret(),], next_page_token="ghi", + ), + service.ListSecretsResponse( + secrets=[resources.Secret(), resources.Secret(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_secrets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_secret( + transport: str = "grpc", request_type=service.CreateSecretRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret(name="name_value",) + + response = client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.CreateSecretRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_create_secret_from_dict(): + test_create_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.CreateSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Secret(name="name_value",) + ) + + response = await client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_create_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecretRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_secret), "__call__") as call: + call.return_value = resources.Secret() + + client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateSecretRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + + await client.create_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_secret( + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].secret_id == "secret_id_value" + + assert args[0].secret == resources.Secret(name="name_value") + + +def test_create_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_secret( + service.CreateSecretRequest(), + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_secret( + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].secret_id == "secret_id_value" + + assert args[0].secret == resources.Secret(name="name_value") + + +@pytest.mark.asyncio +async def test_create_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_secret( + service.CreateSecretRequest(), + parent="parent_value", + secret_id="secret_id_value", + secret=resources.Secret(name="name_value"), + ) + + +def test_add_secret_version( + transport: str = "grpc", request_type=service.AddSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.AddSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_add_secret_version_from_dict(): + test_add_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_add_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.AddSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_add_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AddSecretVersionRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AddSecretVersionRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.add_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_add_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_secret_version( + parent="parent_value", payload=resources.SecretPayload(data=b"data_blob"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].payload == resources.SecretPayload(data=b"data_blob") + + +def test_add_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_secret_version( + service.AddSecretVersionRequest(), + parent="parent_value", + payload=resources.SecretPayload(data=b"data_blob"), + ) + + +@pytest.mark.asyncio +async def test_add_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_secret_version( + parent="parent_value", payload=resources.SecretPayload(data=b"data_blob"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].payload == resources.SecretPayload(data=b"data_blob") + + +@pytest.mark.asyncio +async def test_add_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_secret_version( + service.AddSecretVersionRequest(), + parent="parent_value", + payload=resources.SecretPayload(data=b"data_blob"), + ) + + +def test_get_secret(transport: str = "grpc", request_type=service.GetSecretRequest): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret(name="name_value",) + + response = client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetSecretRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_get_secret_from_dict(): + test_get_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.GetSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Secret(name="name_value",) + ) + + response = await client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_get_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_secret), "__call__") as call: + call.return_value = resources.Secret() + + client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + + await client.get_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_secret( + service.GetSecretRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_secret( + service.GetSecretRequest(), name="name_value", + ) + + +def test_update_secret( + transport: str = "grpc", request_type=service.UpdateSecretRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret(name="name_value",) + + response = client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.UpdateSecretRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_update_secret_from_dict(): + test_update_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.UpdateSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Secret(name="name_value",) + ) + + response = await client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Secret) + + assert response.name == "name_value" + + +def test_update_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateSecretRequest() + request.secret.name = "secret.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_secret), "__call__") as call: + call.return_value = resources.Secret() + + client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "secret.name=secret.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateSecretRequest() + request.secret.name = "secret.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + + await client.update_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "secret.name=secret.name/value",) in kw["metadata"] + + +def test_update_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_secret( + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].secret == resources.Secret(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_secret( + service.UpdateSecretRequest(), + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Secret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Secret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_secret( + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].secret == resources.Secret(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_secret( + service.UpdateSecretRequest(), + secret=resources.Secret(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_secret( + transport: str = "grpc", request_type=service.DeleteSecretRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DeleteSecretRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_secret_from_dict(): + test_delete_secret(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_secret_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.DeleteSecretRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_secret_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_secret), "__call__") as call: + call.return_value = None + + client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteSecretRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_secret), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_secret_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_secret_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_secret( + service.DeleteSecretRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_secret), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_secret(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_secret( + service.DeleteSecretRequest(), name="name_value", + ) + + +def test_list_secret_versions( + transport: str = "grpc", request_type=service.ListSecretVersionsRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretVersionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + + response = client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListSecretVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretVersionsPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secret_versions_from_dict(): + test_list_secret_versions(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_secret_versions_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.ListSecretVersionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretVersionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + ) + + response = await client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretVersionsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + assert response.total_size == 1086 + + +def test_list_secret_versions_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretVersionsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + call.return_value = service.ListSecretVersionsResponse() + + client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_secret_versions_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSecretVersionsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretVersionsResponse() + ) + + await client.list_secret_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_secret_versions_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretVersionsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_secret_versions(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_secret_versions_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_secret_versions( + service.ListSecretVersionsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_secret_versions_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSecretVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSecretVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_secret_versions(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_secret_versions_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_secret_versions( + service.ListSecretVersionsRequest(), parent="parent_value", + ) + + +def test_list_secret_versions_pager(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_secret_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.SecretVersion) for i in results) + + +def test_list_secret_versions_pages(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_secret_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + pages = list(client.list_secret_versions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_secret_versions_async_pager(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + async_pager = await client.list_secret_versions(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SecretVersion) for i in responses) + + +@pytest.mark.asyncio +async def test_list_secret_versions_async_pages(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_secret_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSecretVersionsResponse( + versions=[ + resources.SecretVersion(), + resources.SecretVersion(), + resources.SecretVersion(), + ], + next_page_token="abc", + ), + service.ListSecretVersionsResponse(versions=[], next_page_token="def",), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(),], next_page_token="ghi", + ), + service.ListSecretVersionsResponse( + versions=[resources.SecretVersion(), resources.SecretVersion(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_secret_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_secret_version( + transport: str = "grpc", request_type=service.GetSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_get_secret_version_from_dict(): + test_get_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.GetSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_get_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.get_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_secret_version( + service.GetSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_secret_version( + service.GetSecretVersionRequest(), name="name_value", + ) + + +def test_access_secret_version( + transport: str = "grpc", request_type=service.AccessSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AccessSecretVersionResponse(name="name_value",) + + response = client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.AccessSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AccessSecretVersionResponse) + + assert response.name == "name_value" + + +def test_access_secret_version_from_dict(): + test_access_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_access_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.AccessSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AccessSecretVersionResponse(name="name_value",) + ) + + response = await client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AccessSecretVersionResponse) + + assert response.name == "name_value" + + +def test_access_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AccessSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.access_secret_version), "__call__" + ) as call: + call.return_value = service.AccessSecretVersionResponse() + + client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_access_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AccessSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.access_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AccessSecretVersionResponse() + ) + + await client.access_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_access_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AccessSecretVersionResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.access_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_access_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.access_secret_version( + service.AccessSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_access_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.access_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AccessSecretVersionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AccessSecretVersionResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.access_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_access_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.access_secret_version( + service.AccessSecretVersionRequest(), name="name_value", + ) + + +def test_disable_secret_version( + transport: str = "grpc", request_type=service.DisableSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DisableSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_disable_secret_version_from_dict(): + test_disable_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_disable_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.DisableSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_disable_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DisableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.disable_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_disable_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DisableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.disable_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.disable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_disable_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.disable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_disable_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.disable_secret_version( + service.DisableSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_disable_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.disable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.disable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_disable_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.disable_secret_version( + service.DisableSecretVersionRequest(), name="name_value", + ) + + +def test_enable_secret_version( + transport: str = "grpc", request_type=service.EnableSecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.EnableSecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_enable_secret_version_from_dict(): + test_enable_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_enable_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.EnableSecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_enable_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EnableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.enable_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_enable_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EnableSecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.enable_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.enable_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_enable_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.enable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_enable_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enable_secret_version( + service.EnableSecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_enable_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.enable_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.enable_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_enable_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.enable_secret_version( + service.EnableSecretVersionRequest(), name="name_value", + ) + + +def test_destroy_secret_version( + transport: str = "grpc", request_type=service.DestroySecretVersionRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + + response = client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DestroySecretVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_destroy_secret_version_from_dict(): + test_destroy_secret_version(request_type=dict) + + +@pytest.mark.asyncio +async def test_destroy_secret_version_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = service.DestroySecretVersionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", state=resources.SecretVersion.State.ENABLED, + ) + ) + + response = await client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + + assert response.name == "name_value" + + assert response.state == resources.SecretVersion.State.ENABLED + + +def test_destroy_secret_version_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroySecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.destroy_secret_version), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + + client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_destroy_secret_version_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroySecretVersionRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.destroy_secret_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + + await client.destroy_secret_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_destroy_secret_version_flattened(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.destroy_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_destroy_secret_version_flattened_error(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.destroy_secret_version( + service.DestroySecretVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_destroy_secret_version_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.destroy_secret_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.destroy_secret_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_destroy_secret_version_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.destroy_secret_version( + service.DestroySecretVersionRequest(), name="name_value", + ) + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + call.return_value = policy.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy( + transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + call.return_value = policy.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecretManagerServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecretManagerServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = SecretManagerServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecretManagerServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecretManagerServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecretManagerServiceGrpcTransport, + transports.SecretManagerServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecretManagerServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.SecretManagerServiceGrpcTransport,) + + +def test_secret_manager_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.SecretManagerServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_secret_manager_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.secretmanager_v1beta1.services.secret_manager_service.transports.SecretManagerServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SecretManagerServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_secrets", + "create_secret", + "add_secret_version", + "get_secret", + "update_secret", + "delete_secret", + "list_secret_versions", + "get_secret_version", + "access_secret_version", + "disable_secret_version", + "enable_secret_version", + "destroy_secret_version", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_secret_manager_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.secretmanager_v1beta1.services.secret_manager_service.transports.SecretManagerServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.SecretManagerServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_secret_manager_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.secretmanager_v1beta1.services.secret_manager_service.transports.SecretManagerServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.SecretManagerServiceTransport() + adc.assert_called_once() + + +def test_secret_manager_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SecretManagerServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_secret_manager_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SecretManagerServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_secret_manager_service_host_no_port(): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="secretmanager.googleapis.com" + ), + ) + assert client._transport._host == "secretmanager.googleapis.com:443" + + +def test_secret_manager_service_host_with_port(): + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="secretmanager.googleapis.com:8000" + ), + ) + assert client._transport._host == "secretmanager.googleapis.com:8000" + + +def test_secret_manager_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.SecretManagerServiceGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_secret_manager_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.SecretManagerServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecretManagerServiceGrpcTransport, + transports.SecretManagerServiceGrpcAsyncIOTransport, + ], +) +def test_secret_manager_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecretManagerServiceGrpcTransport, + transports.SecretManagerServiceGrpcAsyncIOTransport, + ], +) +def test_secret_manager_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_secret_path(): + project = "squid" + secret = "clam" + + expected = "projects/{project}/secrets/{secret}".format( + project=project, secret=secret, + ) + actual = SecretManagerServiceClient.secret_path(project, secret) + assert expected == actual + + +def test_parse_secret_path(): + expected = { + "project": "whelk", + "secret": "octopus", + } + path = SecretManagerServiceClient.secret_path(**expected) + + # Check that the path construction is reversible. + actual = SecretManagerServiceClient.parse_secret_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.SecretManagerServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SecretManagerServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SecretManagerServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SecretManagerServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/v1/test_secret_manager_service_client_v1.py b/tests/unit/gapic/v1/test_secret_manager_service_client_v1.py deleted file mode 100644 index 3f71ad8..0000000 --- a/tests/unit/gapic/v1/test_secret_manager_service_client_v1.py +++ /dev/null @@ -1,674 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import secretmanager_v1 -from google.cloud.secretmanager_v1.proto import resources_pb2 -from google.cloud.secretmanager_v1.proto import service_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestSecretManagerServiceClient(object): - def test_list_secrets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - secrets_element = {} - secrets = [secrets_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "secrets": secrets, - } - expected_response = service_pb2.ListSecretsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - parent = client.project_path("[PROJECT]") - - paged_list_response = client.list_secrets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.secrets[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = service_pb2.ListSecretsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_secrets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - parent = client.project_path("[PROJECT]") - - paged_list_response = client.list_secrets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_create_secret(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = resources_pb2.Secret(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - parent = client.project_path("[PROJECT]") - secret_id = "secretId-739547894" - secret = {} - - response = client.create_secret(parent, secret_id, secret) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.CreateSecretRequest( - parent=parent, secret_id=secret_id, secret=secret - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - parent = client.project_path("[PROJECT]") - secret_id = "secretId-739547894" - secret = {} - - with pytest.raises(CustomException): - client.create_secret(parent, secret_id, secret) - - def test_add_secret_version(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - parent = client.secret_path("[PROJECT]", "[SECRET]") - payload = {} - - response = client.add_secret_version(parent, payload) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.AddSecretVersionRequest( - parent=parent, payload=payload - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_add_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - parent = client.secret_path("[PROJECT]", "[SECRET]") - payload = {} - - with pytest.raises(CustomException): - client.add_secret_version(parent, payload) - - def test_get_secret(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.Secret(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_path("[PROJECT]", "[SECRET]") - - response = client.get_secret(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.GetSecretRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_path("[PROJECT]", "[SECRET]") - - with pytest.raises(CustomException): - client.get_secret(name) - - def test_update_secret(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = resources_pb2.Secret(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - secret = {} - update_mask = {} - - response = client.update_secret(secret, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.UpdateSecretRequest( - secret=secret, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - secret = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_secret(secret, update_mask) - - def test_delete_secret(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_path("[PROJECT]", "[SECRET]") - - client.delete_secret(name) - - assert len(channel.requests) == 1 - expected_request = service_pb2.DeleteSecretRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_path("[PROJECT]", "[SECRET]") - - with pytest.raises(CustomException): - client.delete_secret(name) - - def test_list_secret_versions(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - versions_element = {} - versions = [versions_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "versions": versions, - } - expected_response = service_pb2.ListSecretVersionsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - parent = client.secret_path("[PROJECT]", "[SECRET]") - - paged_list_response = client.list_secret_versions(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.versions[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = service_pb2.ListSecretVersionsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_secret_versions_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - parent = client.secret_path("[PROJECT]", "[SECRET]") - - paged_list_response = client.list_secret_versions(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.get_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.GetSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.get_secret_version(name) - - def test_access_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = service_pb2.AccessSecretVersionResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.access_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.AccessSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_access_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.access_secret_version(name) - - def test_disable_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.disable_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.DisableSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_disable_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.disable_secret_version(name) - - def test_enable_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.enable_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.EnableSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_enable_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.enable_secret_version(name) - - def test_destroy_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.destroy_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.DestroySecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_destroy_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.destroy_secret_version(name) - - def test_set_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - resource = "resource-341064690" - policy = {} - - response = client.set_iam_policy(resource, policy) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - resource = "resource-341064690" - policy = {} - - with pytest.raises(CustomException): - client.set_iam_policy(resource, policy) - - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1.SecretManagerServiceClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) diff --git a/tests/unit/gapic/v1beta1/test_secret_manager_service_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_secret_manager_service_client_v1beta1.py deleted file mode 100644 index bbbb352..0000000 --- a/tests/unit/gapic/v1beta1/test_secret_manager_service_client_v1beta1.py +++ /dev/null @@ -1,674 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import secretmanager_v1beta1 -from google.cloud.secretmanager_v1beta1.proto import resources_pb2 -from google.cloud.secretmanager_v1beta1.proto import service_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestSecretManagerServiceClient(object): - def test_list_secrets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - secrets_element = {} - secrets = [secrets_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "secrets": secrets, - } - expected_response = service_pb2.ListSecretsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - parent = client.project_path("[PROJECT]") - - paged_list_response = client.list_secrets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.secrets[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = service_pb2.ListSecretsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_secrets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - parent = client.project_path("[PROJECT]") - - paged_list_response = client.list_secrets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_create_secret(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = resources_pb2.Secret(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - parent = client.project_path("[PROJECT]") - secret_id = "secretId-739547894" - secret = {} - - response = client.create_secret(parent, secret_id, secret) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.CreateSecretRequest( - parent=parent, secret_id=secret_id, secret=secret - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - parent = client.project_path("[PROJECT]") - secret_id = "secretId-739547894" - secret = {} - - with pytest.raises(CustomException): - client.create_secret(parent, secret_id, secret) - - def test_add_secret_version(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - parent = client.secret_path("[PROJECT]", "[SECRET]") - payload = {} - - response = client.add_secret_version(parent, payload) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.AddSecretVersionRequest( - parent=parent, payload=payload - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_add_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - parent = client.secret_path("[PROJECT]", "[SECRET]") - payload = {} - - with pytest.raises(CustomException): - client.add_secret_version(parent, payload) - - def test_get_secret(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.Secret(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_path("[PROJECT]", "[SECRET]") - - response = client.get_secret(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.GetSecretRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_path("[PROJECT]", "[SECRET]") - - with pytest.raises(CustomException): - client.get_secret(name) - - def test_update_secret(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = resources_pb2.Secret(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - secret = {} - update_mask = {} - - response = client.update_secret(secret, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.UpdateSecretRequest( - secret=secret, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - secret = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_secret(secret, update_mask) - - def test_delete_secret(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_path("[PROJECT]", "[SECRET]") - - client.delete_secret(name) - - assert len(channel.requests) == 1 - expected_request = service_pb2.DeleteSecretRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_secret_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_path("[PROJECT]", "[SECRET]") - - with pytest.raises(CustomException): - client.delete_secret(name) - - def test_list_secret_versions(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - versions_element = {} - versions = [versions_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "versions": versions, - } - expected_response = service_pb2.ListSecretVersionsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - parent = client.secret_path("[PROJECT]", "[SECRET]") - - paged_list_response = client.list_secret_versions(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.versions[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = service_pb2.ListSecretVersionsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_secret_versions_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - parent = client.secret_path("[PROJECT]", "[SECRET]") - - paged_list_response = client.list_secret_versions(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.get_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.GetSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.get_secret_version(name) - - def test_access_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = service_pb2.AccessSecretVersionResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.access_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.AccessSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_access_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.access_secret_version(name) - - def test_disable_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.disable_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.DisableSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_disable_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.disable_secret_version(name) - - def test_enable_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.enable_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.EnableSecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_enable_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.enable_secret_version(name) - - def test_destroy_secret_version(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = resources_pb2.SecretVersion(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - response = client.destroy_secret_version(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = service_pb2.DestroySecretVersionRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_destroy_secret_version_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - name = client.secret_version_path("[PROJECT]", "[SECRET]", "[SECRET_VERSION]") - - with pytest.raises(CustomException): - client.destroy_secret_version(name) - - def test_set_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - resource = "resource-341064690" - policy = {} - - response = client.set_iam_policy(resource, policy) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - resource = "resource-341064690" - policy = {} - - with pytest.raises(CustomException): - client.set_iam_policy(resource, policy) - - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = secretmanager_v1beta1.SecretManagerServiceClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions)