structure saas with tools

This commit is contained in:
Davidson Gomes
2025-04-25 15:30:54 -03:00
commit 1aef473937
16434 changed files with 6584257 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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_v1beta1 import gapic_version as package_version
__version__ = package_version.__version__
from .services.secret_manager_service import (
SecretManagerServiceAsyncClient,
SecretManagerServiceClient,
)
from .types.resources import Replication, Secret, SecretPayload, SecretVersion
from .types.service import (
AccessSecretVersionRequest,
AccessSecretVersionResponse,
AddSecretVersionRequest,
CreateSecretRequest,
DeleteSecretRequest,
DestroySecretVersionRequest,
DisableSecretVersionRequest,
EnableSecretVersionRequest,
GetSecretRequest,
GetSecretVersionRequest,
ListSecretsRequest,
ListSecretsResponse,
ListSecretVersionsRequest,
ListSecretVersionsResponse,
UpdateSecretRequest,
)
__all__ = (
"SecretManagerServiceAsyncClient",
"AccessSecretVersionRequest",
"AccessSecretVersionResponse",
"AddSecretVersionRequest",
"CreateSecretRequest",
"DeleteSecretRequest",
"DestroySecretVersionRequest",
"DisableSecretVersionRequest",
"EnableSecretVersionRequest",
"GetSecretRequest",
"GetSecretVersionRequest",
"ListSecretVersionsRequest",
"ListSecretVersionsResponse",
"ListSecretsRequest",
"ListSecretsResponse",
"Replication",
"Secret",
"SecretManagerServiceClient",
"SecretPayload",
"SecretVersion",
"UpdateSecretRequest",
)

View File

@@ -0,0 +1,253 @@
{
"comment": "This file maps proto services/RPCs to the corresponding library clients/methods",
"language": "python",
"libraryPackage": "google.cloud.secretmanager_v1beta1",
"protoPackage": "google.cloud.secrets.v1beta1",
"schema": "1.0",
"services": {
"SecretManagerService": {
"clients": {
"grpc": {
"libraryClient": "SecretManagerServiceClient",
"rpcs": {
"AccessSecretVersion": {
"methods": [
"access_secret_version"
]
},
"AddSecretVersion": {
"methods": [
"add_secret_version"
]
},
"CreateSecret": {
"methods": [
"create_secret"
]
},
"DeleteSecret": {
"methods": [
"delete_secret"
]
},
"DestroySecretVersion": {
"methods": [
"destroy_secret_version"
]
},
"DisableSecretVersion": {
"methods": [
"disable_secret_version"
]
},
"EnableSecretVersion": {
"methods": [
"enable_secret_version"
]
},
"GetIamPolicy": {
"methods": [
"get_iam_policy"
]
},
"GetSecret": {
"methods": [
"get_secret"
]
},
"GetSecretVersion": {
"methods": [
"get_secret_version"
]
},
"ListSecretVersions": {
"methods": [
"list_secret_versions"
]
},
"ListSecrets": {
"methods": [
"list_secrets"
]
},
"SetIamPolicy": {
"methods": [
"set_iam_policy"
]
},
"TestIamPermissions": {
"methods": [
"test_iam_permissions"
]
},
"UpdateSecret": {
"methods": [
"update_secret"
]
}
}
},
"grpc-async": {
"libraryClient": "SecretManagerServiceAsyncClient",
"rpcs": {
"AccessSecretVersion": {
"methods": [
"access_secret_version"
]
},
"AddSecretVersion": {
"methods": [
"add_secret_version"
]
},
"CreateSecret": {
"methods": [
"create_secret"
]
},
"DeleteSecret": {
"methods": [
"delete_secret"
]
},
"DestroySecretVersion": {
"methods": [
"destroy_secret_version"
]
},
"DisableSecretVersion": {
"methods": [
"disable_secret_version"
]
},
"EnableSecretVersion": {
"methods": [
"enable_secret_version"
]
},
"GetIamPolicy": {
"methods": [
"get_iam_policy"
]
},
"GetSecret": {
"methods": [
"get_secret"
]
},
"GetSecretVersion": {
"methods": [
"get_secret_version"
]
},
"ListSecretVersions": {
"methods": [
"list_secret_versions"
]
},
"ListSecrets": {
"methods": [
"list_secrets"
]
},
"SetIamPolicy": {
"methods": [
"set_iam_policy"
]
},
"TestIamPermissions": {
"methods": [
"test_iam_permissions"
]
},
"UpdateSecret": {
"methods": [
"update_secret"
]
}
}
},
"rest": {
"libraryClient": "SecretManagerServiceClient",
"rpcs": {
"AccessSecretVersion": {
"methods": [
"access_secret_version"
]
},
"AddSecretVersion": {
"methods": [
"add_secret_version"
]
},
"CreateSecret": {
"methods": [
"create_secret"
]
},
"DeleteSecret": {
"methods": [
"delete_secret"
]
},
"DestroySecretVersion": {
"methods": [
"destroy_secret_version"
]
},
"DisableSecretVersion": {
"methods": [
"disable_secret_version"
]
},
"EnableSecretVersion": {
"methods": [
"enable_secret_version"
]
},
"GetIamPolicy": {
"methods": [
"get_iam_policy"
]
},
"GetSecret": {
"methods": [
"get_secret"
]
},
"GetSecretVersion": {
"methods": [
"get_secret_version"
]
},
"ListSecretVersions": {
"methods": [
"list_secret_versions"
]
},
"ListSecrets": {
"methods": [
"list_secrets"
]
},
"SetIamPolicy": {
"methods": [
"set_iam_policy"
]
},
"TestIamPermissions": {
"methods": [
"test_iam_permissions"
]
},
"UpdateSecret": {
"methods": [
"update_secret"
]
}
}
}
}
}
}
}

View File

@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__version__ = "2.23.3" # {x-release-please-version}

View File

@@ -0,0 +1,2 @@
# Marker file for PEP 561.
# The google-cloud-secretmanager package uses inline types.

View File

@@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

View File

@@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 .async_client import SecretManagerServiceAsyncClient
from .client import SecretManagerServiceClient
__all__ = (
"SecretManagerServiceClient",
"SecretManagerServiceAsyncClient",
)

View File

@@ -0,0 +1,353 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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,
AsyncIterator,
Awaitable,
Callable,
Iterator,
Optional,
Sequence,
Tuple,
Union,
)
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.api_core import retry_async as retries_async
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
OptionalAsyncRetry = Union[
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
from google.cloud.secretmanager_v1beta1.types import resources, service
class ListSecretsPager:
"""A pager for iterating through ``list_secrets`` requests.
This class thinly wraps an initial
:class:`google.cloud.secretmanager_v1beta1.types.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:`google.cloud.secretmanager_v1beta1.types.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,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.secretmanager_v1beta1.types.ListSecretsRequest):
The initial request object.
response (google.cloud.secretmanager_v1beta1.types.ListSecretsResponse):
The initial response object.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = service.ListSecretsRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[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,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __iter__(self) -> Iterator[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:`google.cloud.secretmanager_v1beta1.types.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:`google.cloud.secretmanager_v1beta1.types.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,
*,
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.secretmanager_v1beta1.types.ListSecretsRequest):
The initial request object.
response (google.cloud.secretmanager_v1beta1.types.ListSecretsResponse):
The initial response object.
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = service.ListSecretsRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
async def pages(self) -> AsyncIterator[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,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __aiter__(self) -> AsyncIterator[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:`google.cloud.secretmanager_v1beta1.types.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:`google.cloud.secretmanager_v1beta1.types.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,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.secretmanager_v1beta1.types.ListSecretVersionsRequest):
The initial request object.
response (google.cloud.secretmanager_v1beta1.types.ListSecretVersionsResponse):
The initial response object.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = service.ListSecretVersionsRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[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,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __iter__(self) -> Iterator[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:`google.cloud.secretmanager_v1beta1.types.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:`google.cloud.secretmanager_v1beta1.types.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,
*,
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.secretmanager_v1beta1.types.ListSecretVersionsRequest):
The initial request object.
response (google.cloud.secretmanager_v1beta1.types.ListSecretVersionsResponse):
The initial response object.
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = service.ListSecretVersionsRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
async def pages(self) -> AsyncIterator[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,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __aiter__(self) -> AsyncIterator[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)

View File

@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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
from .rest import SecretManagerServiceRestInterceptor, SecretManagerServiceRestTransport
# Compile a registry of transports.
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[SecretManagerServiceTransport]]
_transport_registry["grpc"] = SecretManagerServiceGrpcTransport
_transport_registry["grpc_asyncio"] = SecretManagerServiceGrpcAsyncIOTransport
_transport_registry["rest"] = SecretManagerServiceRestTransport
__all__ = (
"SecretManagerServiceTransport",
"SecretManagerServiceGrpcTransport",
"SecretManagerServiceGrpcAsyncIOTransport",
"SecretManagerServiceRestTransport",
"SecretManagerServiceRestInterceptor",
)

View File

@@ -0,0 +1,410 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.iam.v1 import policy_pb2 # type: ignore
from google.oauth2 import service_account # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.cloud.secretmanager_v1beta1 import gapic_version as package_version
from google.cloud.secretmanager_v1beta1.types import resources, service
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=package_version.__version__
)
class SecretManagerServiceTransport(abc.ABC):
"""Abstract transport class for SecretManagerService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
DEFAULT_HOST: str = "secretmanager.googleapis.com"
def __init__(
self,
*,
host: str = DEFAULT_HOST,
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
api_audience: Optional[str] = None,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to (default: 'secretmanager.googleapis.com').
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
"""
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
# Save the scopes.
self._scopes = scopes
if not hasattr(self, "_ignore_credentials"):
self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
raise core_exceptions.DuplicateCredentialArgs(
"'credentials_file' and 'credentials' are mutually exclusive"
)
if credentials_file is not None:
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None and not self._ignore_credentials:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
# Don't apply audience if the credentials file passed from user.
if hasattr(credentials, "with_gdch_audience"):
credentials = credentials.with_gdch_audience(
api_audience if api_audience else host
)
# If the credentials are service account credentials, then always try to use self signed JWT.
if (
always_use_jwt_access
and isinstance(credentials, service_account.Credentials)
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
):
credentials = credentials.with_always_use_jwt_access(True)
# Save the credentials.
self._credentials = credentials
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
@property
def host(self):
return self._host
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(
core_exceptions.ServiceUnavailable,
core_exceptions.Unknown,
),
deadline=60.0,
),
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,
),
self.get_location: gapic_v1.method.wrap_method(
self.get_location,
default_timeout=None,
client_info=client_info,
),
self.list_locations: gapic_v1.method.wrap_method(
self.list_locations,
default_timeout=None,
client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def list_secrets(
self,
) -> Callable[
[service.ListSecretsRequest],
Union[service.ListSecretsResponse, Awaitable[service.ListSecretsResponse]],
]:
raise NotImplementedError()
@property
def create_secret(
self,
) -> Callable[
[service.CreateSecretRequest],
Union[resources.Secret, Awaitable[resources.Secret]],
]:
raise NotImplementedError()
@property
def add_secret_version(
self,
) -> Callable[
[service.AddSecretVersionRequest],
Union[resources.SecretVersion, Awaitable[resources.SecretVersion]],
]:
raise NotImplementedError()
@property
def get_secret(
self,
) -> Callable[
[service.GetSecretRequest], Union[resources.Secret, Awaitable[resources.Secret]]
]:
raise NotImplementedError()
@property
def update_secret(
self,
) -> Callable[
[service.UpdateSecretRequest],
Union[resources.Secret, Awaitable[resources.Secret]],
]:
raise NotImplementedError()
@property
def delete_secret(
self,
) -> Callable[
[service.DeleteSecretRequest],
Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_secret_versions(
self,
) -> Callable[
[service.ListSecretVersionsRequest],
Union[
service.ListSecretVersionsResponse,
Awaitable[service.ListSecretVersionsResponse],
],
]:
raise NotImplementedError()
@property
def get_secret_version(
self,
) -> Callable[
[service.GetSecretVersionRequest],
Union[resources.SecretVersion, Awaitable[resources.SecretVersion]],
]:
raise NotImplementedError()
@property
def access_secret_version(
self,
) -> Callable[
[service.AccessSecretVersionRequest],
Union[
service.AccessSecretVersionResponse,
Awaitable[service.AccessSecretVersionResponse],
],
]:
raise NotImplementedError()
@property
def disable_secret_version(
self,
) -> Callable[
[service.DisableSecretVersionRequest],
Union[resources.SecretVersion, Awaitable[resources.SecretVersion]],
]:
raise NotImplementedError()
@property
def enable_secret_version(
self,
) -> Callable[
[service.EnableSecretVersionRequest],
Union[resources.SecretVersion, Awaitable[resources.SecretVersion]],
]:
raise NotImplementedError()
@property
def destroy_secret_version(
self,
) -> Callable[
[service.DestroySecretVersionRequest],
Union[resources.SecretVersion, Awaitable[resources.SecretVersion]],
]:
raise NotImplementedError()
@property
def set_iam_policy(
self,
) -> Callable[
[iam_policy_pb2.SetIamPolicyRequest],
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
]:
raise NotImplementedError()
@property
def get_iam_policy(
self,
) -> Callable[
[iam_policy_pb2.GetIamPolicyRequest],
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
]:
raise NotImplementedError()
@property
def test_iam_permissions(
self,
) -> Callable[
[iam_policy_pb2.TestIamPermissionsRequest],
Union[
iam_policy_pb2.TestIamPermissionsResponse,
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
],
]:
raise NotImplementedError()
@property
def get_location(
self,
) -> Callable[
[locations_pb2.GetLocationRequest],
Union[locations_pb2.Location, Awaitable[locations_pb2.Location]],
]:
raise NotImplementedError()
@property
def list_locations(
self,
) -> Callable[
[locations_pb2.ListLocationsRequest],
Union[
locations_pb2.ListLocationsResponse,
Awaitable[locations_pb2.ListLocationsResponse],
],
]:
raise NotImplementedError()
@property
def kind(self) -> str:
raise NotImplementedError()
__all__ = ("SecretManagerServiceTransport",)

View File

@@ -0,0 +1,823 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 json
import logging as std_logging
import pickle
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
from google.api_core import gapic_v1, grpc_helpers
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.iam.v1 import policy_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
from google.cloud.secretmanager_v1beta1.types import resources, service
from .base import DEFAULT_CLIENT_INFO, SecretManagerServiceTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
def intercept_unary_unary(self, continuation, client_call_details, request):
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
)
if logging_enabled: # pragma: NO COVER
request_metadata = client_call_details.metadata
if isinstance(request, proto.Message):
request_payload = type(request).to_json(request)
elif isinstance(request, google.protobuf.message.Message):
request_payload = MessageToJson(request)
else:
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
request_metadata = {
key: value.decode("utf-8") if isinstance(value, bytes) else value
for key, value in request_metadata
}
grpc_request = {
"payload": request_payload,
"requestMethod": "grpc",
"metadata": dict(request_metadata),
}
_LOGGER.debug(
f"Sending request for {client_call_details.method}",
extra={
"serviceName": "google.cloud.secrets.v1beta1.SecretManagerService",
"rpcName": str(client_call_details.method),
"request": grpc_request,
"metadata": grpc_request["metadata"],
},
)
response = continuation(client_call_details, request)
if logging_enabled: # pragma: NO COVER
response_metadata = response.trailing_metadata()
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
metadata = (
dict([(k, str(v)) for k, v in response_metadata])
if response_metadata
else None
)
result = response.result()
if isinstance(result, proto.Message):
response_payload = type(result).to_json(result)
elif isinstance(result, google.protobuf.message.Message):
response_payload = MessageToJson(result)
else:
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
grpc_response = {
"payload": response_payload,
"metadata": metadata,
"status": "OK",
}
_LOGGER.debug(
f"Received response for {client_call_details.method}.",
extra={
"serviceName": "google.cloud.secrets.v1beta1.SecretManagerService",
"rpcName": client_call_details.method,
"response": grpc_response,
"metadata": grpc_response["metadata"],
},
)
return response
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: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
api_mtls_endpoint: Optional[str] = None,
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
api_audience: Optional[str] = None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to (default: 'secretmanager.googleapis.com').
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 a ``channel`` instance 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 a ``channel`` instance is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if a ``channel`` instance is provided.
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
A ``Channel`` instance through which to make calls, or a Callable
that constructs and returns one. If set to None, ``self.create_channel``
is used to create the channel. If a Callable is given, it will be called
with the same arguments as used in ``self.create_channel``.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for the grpc channel. It is ignored if a ``channel`` instance is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure a mutual TLS channel. It is
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
credentials = None
self._ignore_credentials = True
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
api_audience=api_audience,
)
if not self._grpc_channel:
# initialize with the provided callable or the default channel
channel_init = channel or type(self).create_channel
self._grpc_channel = channel_init(
self._host,
# use the credentials which are saved
credentials=self._credentials,
# Set ``credentials_file`` to ``None`` here as
# the credentials that we saved earlier should be used.
credentials_file=None,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
self._interceptor = _LoggingClientInterceptor()
self._logged_channel = grpc.intercept_channel(
self._grpc_channel, self._interceptor
)
# Wrap messages. This must be done after self._logged_channel exists
self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "secretmanager.googleapis.com",
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service."""
return self._grpc_channel
@property
def 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._logged_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._logged_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._logged_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._logged_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._logged_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_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/DeleteSecret",
request_serializer=service.DeleteSecretRequest.serialize,
response_deserializer=empty_pb2.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._logged_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._logged_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._logged_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._logged_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._logged_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._logged_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_pb2.SetIamPolicyRequest], policy_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/SetIamPolicy",
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
response_deserializer=policy_pb2.Policy.FromString,
)
return self._stubs["set_iam_policy"]
@property
def get_iam_policy(
self,
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/GetIamPolicy",
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
response_deserializer=policy_pb2.Policy.FromString,
)
return self._stubs["get_iam_policy"]
@property
def test_iam_permissions(
self,
) -> Callable[
[iam_policy_pb2.TestIamPermissionsRequest],
iam_policy_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/TestIamPermissions",
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
)
return self._stubs["test_iam_permissions"]
def close(self):
self._logged_channel.close()
@property
def list_locations(
self,
) -> Callable[
[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse
]:
r"""Return a callable for the list locations method over gRPC."""
# Generate a "stub function" on-the-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_locations" not in self._stubs:
self._stubs["list_locations"] = self._logged_channel.unary_unary(
"/google.cloud.location.Locations/ListLocations",
request_serializer=locations_pb2.ListLocationsRequest.SerializeToString,
response_deserializer=locations_pb2.ListLocationsResponse.FromString,
)
return self._stubs["list_locations"]
@property
def get_location(
self,
) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]:
r"""Return a callable for the list locations method over gRPC."""
# Generate a "stub function" on-the-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_location" not in self._stubs:
self._stubs["get_location"] = self._logged_channel.unary_unary(
"/google.cloud.location.Locations/GetLocation",
request_serializer=locations_pb2.GetLocationRequest.SerializeToString,
response_deserializer=locations_pb2.Location.FromString,
)
return self._stubs["get_location"]
@property
def kind(self) -> str:
return "grpc"
__all__ = ("SecretManagerServiceGrpcTransport",)

View File

@@ -0,0 +1,952 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 inspect
import json
import logging as std_logging
import pickle
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, grpc_helpers_async
from google.api_core import retry_async as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.iam.v1 import policy_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
import google.protobuf.message
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
import proto # type: ignore
from google.cloud.secretmanager_v1beta1.types import resources, service
from .base import DEFAULT_CLIENT_INFO, SecretManagerServiceTransport
from .grpc import SecretManagerServiceGrpcTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class _LoggingClientAIOInterceptor(
grpc.aio.UnaryUnaryClientInterceptor
): # pragma: NO COVER
async def intercept_unary_unary(self, continuation, client_call_details, request):
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
)
if logging_enabled: # pragma: NO COVER
request_metadata = client_call_details.metadata
if isinstance(request, proto.Message):
request_payload = type(request).to_json(request)
elif isinstance(request, google.protobuf.message.Message):
request_payload = MessageToJson(request)
else:
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
request_metadata = {
key: value.decode("utf-8") if isinstance(value, bytes) else value
for key, value in request_metadata
}
grpc_request = {
"payload": request_payload,
"requestMethod": "grpc",
"metadata": dict(request_metadata),
}
_LOGGER.debug(
f"Sending request for {client_call_details.method}",
extra={
"serviceName": "google.cloud.secrets.v1beta1.SecretManagerService",
"rpcName": str(client_call_details.method),
"request": grpc_request,
"metadata": grpc_request["metadata"],
},
)
response = await continuation(client_call_details, request)
if logging_enabled: # pragma: NO COVER
response_metadata = await response.trailing_metadata()
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
metadata = (
dict([(k, str(v)) for k, v in response_metadata])
if response_metadata
else None
)
result = await response
if isinstance(result, proto.Message):
response_payload = type(result).to_json(result)
elif isinstance(result, google.protobuf.message.Message):
response_payload = MessageToJson(result)
else:
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
grpc_response = {
"payload": response_payload,
"metadata": metadata,
"status": "OK",
}
_LOGGER.debug(
f"Received response to rpc {client_call_details.method}.",
extra={
"serviceName": "google.cloud.secrets.v1beta1.SecretManagerService",
"rpcName": str(client_call_details.method),
"response": grpc_response,
"metadata": grpc_response["metadata"],
},
)
return response
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: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
aio.Channel: A gRPC AsyncIO channel object.
"""
return grpc_helpers_async.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
)
def __init__(
self,
*,
host: str = "secretmanager.googleapis.com",
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
api_mtls_endpoint: Optional[str] = None,
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
api_audience: Optional[str] = None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to (default: 'secretmanager.googleapis.com').
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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]):
A ``Channel`` instance through which to make calls, or a Callable
that constructs and returns one. If set to None, ``self.create_channel``
is used to create the channel. If a Callable is given, it will be called
with the same arguments as used in ``self.create_channel``.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for the grpc channel. It is ignored if a ``channel`` instance is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure a mutual TLS channel. It is
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
credentials = None
self._ignore_credentials = True
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
api_audience=api_audience,
)
if not self._grpc_channel:
# initialize with the provided callable or the default channel
channel_init = channel or type(self).create_channel
self._grpc_channel = channel_init(
self._host,
# use the credentials which are saved
credentials=self._credentials,
# Set ``credentials_file`` to ``None`` here as
# the credentials that we saved earlier should be used.
credentials_file=None,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
self._interceptor = _LoggingClientAIOInterceptor()
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
self._logged_channel = self._grpc_channel
self._wrap_with_kind = (
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
)
# Wrap messages. This must be done after self._logged_channel exists
self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
"""Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
"""
# Return the channel from cache.
return self._grpc_channel
@property
def 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._logged_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._logged_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._logged_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._logged_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._logged_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_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/DeleteSecret",
request_serializer=service.DeleteSecretRequest.serialize,
response_deserializer=empty_pb2.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._logged_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._logged_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._logged_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._logged_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._logged_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._logged_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_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/SetIamPolicy",
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
response_deserializer=policy_pb2.Policy.FromString,
)
return self._stubs["set_iam_policy"]
@property
def get_iam_policy(
self,
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/GetIamPolicy",
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
response_deserializer=policy_pb2.Policy.FromString,
)
return self._stubs["get_iam_policy"]
@property
def test_iam_permissions(
self,
) -> Callable[
[iam_policy_pb2.TestIamPermissionsRequest],
Awaitable[iam_policy_pb2.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._logged_channel.unary_unary(
"/google.cloud.secrets.v1beta1.SecretManagerService/TestIamPermissions",
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
)
return self._stubs["test_iam_permissions"]
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
self.list_secrets: self._wrap_method(
self.list_secrets,
default_timeout=60.0,
client_info=client_info,
),
self.create_secret: self._wrap_method(
self.create_secret,
default_timeout=60.0,
client_info=client_info,
),
self.add_secret_version: self._wrap_method(
self.add_secret_version,
default_timeout=60.0,
client_info=client_info,
),
self.get_secret: self._wrap_method(
self.get_secret,
default_timeout=60.0,
client_info=client_info,
),
self.update_secret: self._wrap_method(
self.update_secret,
default_timeout=60.0,
client_info=client_info,
),
self.delete_secret: self._wrap_method(
self.delete_secret,
default_timeout=60.0,
client_info=client_info,
),
self.list_secret_versions: self._wrap_method(
self.list_secret_versions,
default_timeout=60.0,
client_info=client_info,
),
self.get_secret_version: self._wrap_method(
self.get_secret_version,
default_timeout=60.0,
client_info=client_info,
),
self.access_secret_version: self._wrap_method(
self.access_secret_version,
default_retry=retries.AsyncRetry(
initial=1.0,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.ServiceUnavailable,
core_exceptions.Unknown,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.disable_secret_version: self._wrap_method(
self.disable_secret_version,
default_timeout=60.0,
client_info=client_info,
),
self.enable_secret_version: self._wrap_method(
self.enable_secret_version,
default_timeout=60.0,
client_info=client_info,
),
self.destroy_secret_version: self._wrap_method(
self.destroy_secret_version,
default_timeout=60.0,
client_info=client_info,
),
self.set_iam_policy: self._wrap_method(
self.set_iam_policy,
default_timeout=60.0,
client_info=client_info,
),
self.get_iam_policy: self._wrap_method(
self.get_iam_policy,
default_timeout=60.0,
client_info=client_info,
),
self.test_iam_permissions: self._wrap_method(
self.test_iam_permissions,
default_timeout=60.0,
client_info=client_info,
),
self.get_location: self._wrap_method(
self.get_location,
default_timeout=None,
client_info=client_info,
),
self.list_locations: self._wrap_method(
self.list_locations,
default_timeout=None,
client_info=client_info,
),
}
def _wrap_method(self, func, *args, **kwargs):
if self._wrap_with_kind: # pragma: NO COVER
kwargs["kind"] = self.kind
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
def close(self):
return self._logged_channel.close()
@property
def kind(self) -> str:
return "grpc_asyncio"
@property
def list_locations(
self,
) -> Callable[
[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse
]:
r"""Return a callable for the list locations method over gRPC."""
# Generate a "stub function" on-the-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_locations" not in self._stubs:
self._stubs["list_locations"] = self._logged_channel.unary_unary(
"/google.cloud.location.Locations/ListLocations",
request_serializer=locations_pb2.ListLocationsRequest.SerializeToString,
response_deserializer=locations_pb2.ListLocationsResponse.FromString,
)
return self._stubs["list_locations"]
@property
def get_location(
self,
) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]:
r"""Return a callable for the list locations method over gRPC."""
# Generate a "stub function" on-the-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_location" not in self._stubs:
self._stubs["get_location"] = self._logged_channel.unary_unary(
"/google.cloud.location.Locations/GetLocation",
request_serializer=locations_pb2.GetLocationRequest.SerializeToString,
response_deserializer=locations_pb2.Location.FromString,
)
return self._stubs["get_location"]
__all__ = ("SecretManagerServiceGrpcAsyncIOTransport",)

View File

@@ -0,0 +1,934 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 json # type: ignore
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1, path_template
from google.cloud.location import locations_pb2 # type: ignore
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.iam.v1 import policy_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
from google.cloud.secretmanager_v1beta1.types import resources, service
from .base import DEFAULT_CLIENT_INFO, SecretManagerServiceTransport
class _BaseSecretManagerServiceRestTransport(SecretManagerServiceTransport):
"""Base REST backend transport for SecretManagerService.
Note: This class is not meant to be used directly. Use its sync and
async sub-classes instead.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
"""
def __init__(
self,
*,
host: str = "secretmanager.googleapis.com",
credentials: Optional[Any] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
url_scheme: str = "https",
api_audience: Optional[str] = None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to (default: 'secretmanager.googleapis.com').
credentials (Optional[Any]): 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.
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 are developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
url_scheme: the protocol scheme for the API endpoint. Normally
"https", but for testing or local servers,
"http" can be specified.
"""
# Run the base constructor
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
if maybe_url_match is None:
raise ValueError(
f"Unexpected hostname structure: {host}"
) # pragma: NO COVER
url_match_items = maybe_url_match.groupdict()
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
api_audience=api_audience,
)
class _BaseAccessSecretVersion:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{name=projects/*/secrets/*/versions/*}:access",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.AccessSecretVersionRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseAccessSecretVersion._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseAddSecretVersion:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{parent=projects/*/secrets/*}:addVersion",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.AddSecretVersionRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseAddSecretVersion._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseCreateSecret:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
"secretId": "",
}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{parent=projects/*}/secrets",
"body": "secret",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.CreateSecretRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseCreateSecret._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseDeleteSecret:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "delete",
"uri": "/v1beta1/{name=projects/*/secrets/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.DeleteSecretRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseDeleteSecret._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseDestroySecretVersion:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{name=projects/*/secrets/*/versions/*}:destroy",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.DestroySecretVersionRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseDestroySecretVersion._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseDisableSecretVersion:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{name=projects/*/secrets/*/versions/*}:disable",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.DisableSecretVersionRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseDisableSecretVersion._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseEnableSecretVersion:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{name=projects/*/secrets/*/versions/*}:enable",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.EnableSecretVersionRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseEnableSecretVersion._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetIamPolicy:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{resource=projects/*/secrets/*}:getIamPolicy",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = request
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseGetIamPolicy._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetSecret:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{name=projects/*/secrets/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.GetSecretRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseGetSecret._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetSecretVersion:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{name=projects/*/secrets/*/versions/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.GetSecretVersionRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseGetSecretVersion._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseListSecrets:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{parent=projects/*}/secrets",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.ListSecretsRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseListSecrets._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseListSecretVersions:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{parent=projects/*/secrets/*}/versions",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.ListSecretVersionsRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseListSecretVersions._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseSetIamPolicy:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{resource=projects/*/secrets/*}:setIamPolicy",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = request
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseSetIamPolicy._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseTestIamPermissions:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1beta1/{resource=projects/*/secrets/*}:testIamPermissions",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = request
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseTestIamPermissions._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseUpdateSecret:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
"updateMask": {},
}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "patch",
"uri": "/v1beta1/{secret.name=projects/*/secrets/*}",
"body": "secret",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = service.UpdateSecretRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSecretManagerServiceRestTransport._BaseUpdateSecret._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetLocation:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{name=projects/*/locations/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
request_kwargs = json_format.MessageToDict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
return query_params
class _BaseListLocations:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1beta1/{name=projects/*}/locations",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
request_kwargs = json_format.MessageToDict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
return query_params
__all__ = ("_BaseSecretManagerServiceRestTransport",)

View File

@@ -0,0 +1,55 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 Replication, Secret, SecretPayload, SecretVersion
from .service import (
AccessSecretVersionRequest,
AccessSecretVersionResponse,
AddSecretVersionRequest,
CreateSecretRequest,
DeleteSecretRequest,
DestroySecretVersionRequest,
DisableSecretVersionRequest,
EnableSecretVersionRequest,
GetSecretRequest,
GetSecretVersionRequest,
ListSecretsRequest,
ListSecretsResponse,
ListSecretVersionsRequest,
ListSecretVersionsResponse,
UpdateSecretRequest,
)
__all__ = (
"Replication",
"Secret",
"SecretPayload",
"SecretVersion",
"AccessSecretVersionRequest",
"AccessSecretVersionResponse",
"AddSecretVersionRequest",
"CreateSecretRequest",
"DeleteSecretRequest",
"DestroySecretVersionRequest",
"DisableSecretVersionRequest",
"EnableSecretVersionRequest",
"GetSecretRequest",
"GetSecretVersionRequest",
"ListSecretsRequest",
"ListSecretsResponse",
"ListSecretVersionsRequest",
"ListSecretVersionsResponse",
"UpdateSecretRequest",
)

View File

@@ -0,0 +1,272 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 annotations
from typing import MutableMapping, MutableSequence
from google.protobuf import timestamp_pb2 # type: ignore
import proto # 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 (google.cloud.secretmanager_v1beta1.types.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 (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time at which the
[Secret][google.cloud.secrets.v1beta1.Secret] was created.
labels (MutableMapping[str, str]):
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: str = proto.Field(
proto.STRING,
number=1,
)
replication: "Replication" = proto.Field(
proto.MESSAGE,
number=2,
message="Replication",
)
create_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=3,
message=timestamp_pb2.Timestamp,
)
labels: MutableMapping[str, str] = 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 (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time at which the
[SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
was created.
destroy_time (google.protobuf.timestamp_pb2.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 (google.cloud.secretmanager_v1beta1.types.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.
Values:
STATE_UNSPECIFIED (0):
Not specified. This value is unused and
invalid.
ENABLED (1):
The
[SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
may be accessed.
DISABLED (2):
The
[SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
may not be accessed, but the secret data is still available
and can be placed back into the
[ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED]
state.
DESTROYED (3):
The
[SecretVersion][google.cloud.secrets.v1beta1.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
name: str = proto.Field(
proto.STRING,
number=1,
)
create_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=2,
message=timestamp_pb2.Timestamp,
)
destroy_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=3,
message=timestamp_pb2.Timestamp,
)
state: State = proto.Field(
proto.ENUM,
number=4,
enum=State,
)
class Replication(proto.Message):
r"""A policy that defines the replication configuration of data.
This message has `oneof`_ fields (mutually exclusive fields).
For each oneof, at most one member field can be set at the same time.
Setting any member of the oneof automatically clears all other
members.
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
Attributes:
automatic (google.cloud.secretmanager_v1beta1.types.Replication.Automatic):
The [Secret][google.cloud.secrets.v1beta1.Secret] will
automatically be replicated without any restrictions.
This field is a member of `oneof`_ ``replication``.
user_managed (google.cloud.secretmanager_v1beta1.types.Replication.UserManaged):
The [Secret][google.cloud.secrets.v1beta1.Secret] will only
be replicated into the locations specified.
This field is a member of `oneof`_ ``replication``.
"""
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
[Replication.UserManaged.replicas][google.cloud.secrets.v1beta1.Replication.UserManaged.replicas]
Attributes:
replicas (MutableSequence[google.cloud.secretmanager_v1beta1.types.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: str = proto.Field(
proto.STRING,
number=1,
)
replicas: MutableSequence[
"Replication.UserManaged.Replica"
] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message="Replication.UserManaged.Replica",
)
automatic: Automatic = proto.Field(
proto.MESSAGE,
number=1,
oneof="replication",
message=Automatic,
)
user_managed: UserManaged = 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: bytes = proto.Field(
proto.BYTES,
number=1,
)
__all__ = tuple(sorted(__protobuf__.manifest))

View File

@@ -0,0 +1,427 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 annotations
from typing import MutableMapping, MutableSequence
from google.protobuf import field_mask_pb2 # type: ignore
import proto # type: ignore
from google.cloud.secretmanager_v1beta1.types import resources
__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: str = proto.Field(
proto.STRING,
number=1,
)
page_size: int = proto.Field(
proto.INT32,
number=2,
)
page_token: str = proto.Field(
proto.STRING,
number=3,
)
class ListSecretsResponse(proto.Message):
r"""Response message for
[SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets].
Attributes:
secrets (MutableSequence[google.cloud.secretmanager_v1beta1.types.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: MutableSequence[resources.Secret] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=resources.Secret,
)
next_page_token: str = proto.Field(
proto.STRING,
number=2,
)
total_size: int = 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 (google.cloud.secretmanager_v1beta1.types.Secret):
Required. A [Secret][google.cloud.secrets.v1beta1.Secret]
with initial field values.
"""
parent: str = proto.Field(
proto.STRING,
number=1,
)
secret_id: str = proto.Field(
proto.STRING,
number=2,
)
secret: resources.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 (google.cloud.secretmanager_v1beta1.types.SecretPayload):
Required. The secret payload of the
[SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
"""
parent: str = proto.Field(
proto.STRING,
number=1,
)
payload: resources.SecretPayload = 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: str = 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: str = proto.Field(
proto.STRING,
number=1,
)
page_size: int = proto.Field(
proto.INT32,
number=2,
)
page_token: str = proto.Field(
proto.STRING,
number=3,
)
class ListSecretVersionsResponse(proto.Message):
r"""Response message for
[SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions].
Attributes:
versions (MutableSequence[google.cloud.secretmanager_v1beta1.types.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: MutableSequence[resources.SecretVersion] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=resources.SecretVersion,
)
next_page_token: str = proto.Field(
proto.STRING,
number=2,
)
total_size: int = 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: str = proto.Field(
proto.STRING,
number=1,
)
class UpdateSecretRequest(proto.Message):
r"""Request message for
[SecretManagerService.UpdateSecret][google.cloud.secrets.v1beta1.SecretManagerService.UpdateSecret].
Attributes:
secret (google.cloud.secretmanager_v1beta1.types.Secret):
Required. [Secret][google.cloud.secrets.v1beta1.Secret] with
updated field values.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. Specifies the fields to be updated.
"""
secret: resources.Secret = proto.Field(
proto.MESSAGE,
number=1,
message=resources.Secret,
)
update_mask: field_mask_pb2.FieldMask = proto.Field(
proto.MESSAGE,
number=2,
message=field_mask_pb2.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: str = 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 (google.cloud.secretmanager_v1beta1.types.SecretPayload):
Secret payload
"""
name: str = proto.Field(
proto.STRING,
number=1,
)
payload: resources.SecretPayload = 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: str = 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: str = 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: str = 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: str = proto.Field(
proto.STRING,
number=1,
)
__all__ = tuple(sorted(__protobuf__.manifest))