- On January 1, 2020 this library will no longer support Python 2 on the latest released version. - Previously released library versions will continue to be available. For more information please + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.
{% block body %} {% endblock %} diff --git a/docs/conf.py b/docs/conf.py index f82a156..6829b2d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,12 +20,16 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" +needs_sphinx = "1.5.5" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -35,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", @@ -90,7 +95,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 25108a1..0000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud OS Login API -============================= - -.. automodule:: google.cloud.oslogin_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 9694a7e..0000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud OS Login API Client -=================================== - -.. automodule:: google.cloud.oslogin_v1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 719f4f9..442c5c6 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,10 +7,22 @@ Api Reference .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + oslogin_v1/services + oslogin_v1/types + oslogin_v1/common/types + changelog +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING + Changelog --------- diff --git a/docs/oslogin_v1/common/types.rst b/docs/oslogin_v1/common/types.rst new file mode 100644 index 0000000..c9c3df7 --- /dev/null +++ b/docs/oslogin_v1/common/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Oslogin Common API +========================================== + +.. automodule:: google.cloud.oslogin_v1.common + :members: diff --git a/docs/oslogin_v1/services.rst b/docs/oslogin_v1/services.rst new file mode 100644 index 0000000..dbdb8bf --- /dev/null +++ b/docs/oslogin_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Oslogin v1 API +======================================== + +.. automodule:: google.cloud.oslogin_v1.services.os_login_service + :members: + :inherited-members: diff --git a/docs/oslogin_v1/types.rst b/docs/oslogin_v1/types.rst new file mode 100644 index 0000000..759411d --- /dev/null +++ b/docs/oslogin_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Oslogin v1 API +===================================== + +.. automodule:: google.cloud.oslogin_v1.types + :members: diff --git a/google/cloud/oslogin/__init__.py b/google/cloud/oslogin/__init__.py new file mode 100644 index 0000000..57af983 --- /dev/null +++ b/google/cloud/oslogin/__init__.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.oslogin_v1.services.os_login_service.async_client import ( + OsLoginServiceAsyncClient, +) +from google.cloud.oslogin_v1.services.os_login_service.client import ( + OsLoginServiceClient, +) +from google.cloud.oslogin_v1.types.oslogin import DeletePosixAccountRequest +from google.cloud.oslogin_v1.types.oslogin import DeleteSshPublicKeyRequest +from google.cloud.oslogin_v1.types.oslogin import GetLoginProfileRequest +from google.cloud.oslogin_v1.types.oslogin import GetSshPublicKeyRequest +from google.cloud.oslogin_v1.types.oslogin import ImportSshPublicKeyRequest +from google.cloud.oslogin_v1.types.oslogin import ImportSshPublicKeyResponse +from google.cloud.oslogin_v1.types.oslogin import LoginProfile +from google.cloud.oslogin_v1.types.oslogin import UpdateSshPublicKeyRequest + +__all__ = ( + "DeletePosixAccountRequest", + "DeleteSshPublicKeyRequest", + "GetLoginProfileRequest", + "GetSshPublicKeyRequest", + "ImportSshPublicKeyRequest", + "ImportSshPublicKeyResponse", + "LoginProfile", + "OsLoginServiceAsyncClient", + "OsLoginServiceClient", + "UpdateSshPublicKeyRequest", +) diff --git a/google/cloud/oslogin/py.typed b/google/cloud/oslogin/py.typed new file mode 100644 index 0000000..825d05f --- /dev/null +++ b/google/cloud/oslogin/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-oslogin package uses inline types. diff --git a/google/cloud/oslogin_v1/__init__.py b/google/cloud/oslogin_v1/__init__.py index 08f98e4..41e41bf 100644 --- a/google/cloud/oslogin_v1/__init__.py +++ b/google/cloud/oslogin_v1/__init__.py @@ -1,45 +1,39 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.oslogin_v1 import types -from google.cloud.oslogin_v1.gapic import enums -from google.cloud.oslogin_v1.gapic import os_login_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class OsLoginServiceClient(os_login_service_client.OsLoginServiceClient): - __doc__ = os_login_service_client.OsLoginServiceClient.__doc__ - enums = enums +from .services.os_login_service import OsLoginServiceClient +from .types.oslogin import DeletePosixAccountRequest +from .types.oslogin import DeleteSshPublicKeyRequest +from .types.oslogin import GetLoginProfileRequest +from .types.oslogin import GetSshPublicKeyRequest +from .types.oslogin import ImportSshPublicKeyRequest +from .types.oslogin import ImportSshPublicKeyResponse +from .types.oslogin import LoginProfile +from .types.oslogin import UpdateSshPublicKeyRequest __all__ = ( - "enums", - "types", + "DeletePosixAccountRequest", + "DeleteSshPublicKeyRequest", + "GetLoginProfileRequest", + "GetSshPublicKeyRequest", + "ImportSshPublicKeyRequest", + "ImportSshPublicKeyResponse", + "LoginProfile", + "UpdateSshPublicKeyRequest", "OsLoginServiceClient", ) diff --git a/google/cloud/oslogin.py b/google/cloud/oslogin_v1/common/__init__.py similarity index 66% rename from google/cloud/oslogin.py rename to google/cloud/oslogin_v1/common/__init__.py index 022d27d..6ac5dc1 100644 --- a/google/cloud/oslogin.py +++ b/google/cloud/oslogin_v1/common/__init__.py @@ -1,29 +1,27 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import - -from google.cloud.oslogin_v1 import OsLoginServiceClient -from google.cloud.oslogin_v1 import enums -from google.cloud.oslogin_v1 import types +from .types.common import OperatingSystemType +from .types.common import PosixAccount +from .types.common import SshPublicKey __all__ = ( - "enums", - "types", - "OsLoginServiceClient", + "OperatingSystemType", + "SshPublicKey", + "PosixAccount", ) diff --git a/google/cloud/oslogin_v1/common/py.typed b/google/cloud/oslogin_v1/common/py.typed new file mode 100644 index 0000000..5f0cbe7 --- /dev/null +++ b/google/cloud/oslogin_v1/common/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-oslogin-common package uses inline types. diff --git a/google/__init__.py b/google/cloud/oslogin_v1/common/types/__init__.py similarity index 71% rename from google/__init__.py rename to google/cloud/oslogin_v1/common/types/__init__.py index 9a1b64a..1f648d3 100644 --- a/google/__init__.py +++ b/google/cloud/oslogin_v1/common/types/__init__.py @@ -1,24 +1,27 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources +from .common import ( + PosixAccount, + SshPublicKey, +) - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "PosixAccount", + "SshPublicKey", +) diff --git a/google/cloud/oslogin_v1/common/types/common.py b/google/cloud/oslogin_v1/common/types/common.py new file mode 100644 index 0000000..52dc2e0 --- /dev/null +++ b/google/cloud/oslogin_v1/common/types/common.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.oslogin.v1", + manifest={"OperatingSystemType", "PosixAccount", "SshPublicKey",}, +) + + +class OperatingSystemType(proto.Enum): + r"""The operating system options for account entries.""" + OPERATING_SYSTEM_TYPE_UNSPECIFIED = 0 + LINUX = 1 + WINDOWS = 2 + + +class PosixAccount(proto.Message): + r"""The POSIX account information associated with a Google + account. + + Attributes: + primary (bool): + Only one POSIX account can be marked as + primary. + username (str): + The username of the POSIX account. + uid (int): + The user ID. + gid (int): + The default group ID. + home_directory (str): + The path to the home directory for this + account. + shell (str): + The path to the logic shell for this account. + gecos (str): + The GECOS (user information) entry for this + account. + system_id (str): + System identifier for which account the + username or uid applies to. By default, the + empty value is used. + account_id (str): + Output only. A POSIX account identifier. + operating_system_type (~.common.OperatingSystemType): + The operating system type where this account + applies. + name (str): + Output only. The canonical resource name. + """ + + primary = proto.Field(proto.BOOL, number=1) + + username = proto.Field(proto.STRING, number=2) + + uid = proto.Field(proto.INT64, number=3) + + gid = proto.Field(proto.INT64, number=4) + + home_directory = proto.Field(proto.STRING, number=5) + + shell = proto.Field(proto.STRING, number=6) + + gecos = proto.Field(proto.STRING, number=7) + + system_id = proto.Field(proto.STRING, number=8) + + account_id = proto.Field(proto.STRING, number=9) + + operating_system_type = proto.Field( + proto.ENUM, number=10, enum="OperatingSystemType", + ) + + name = proto.Field(proto.STRING, number=11) + + +class SshPublicKey(proto.Message): + r"""The SSH public key information associated with a Google + account. + + Attributes: + key (str): + Public key text in SSH format, defined by RFC4253 section + 6.6. + expiration_time_usec (int): + An expiration time in microseconds since + epoch. + fingerprint (str): + Output only. The SHA-256 fingerprint of the + SSH public key. + name (str): + Output only. The canonical resource name. + """ + + key = proto.Field(proto.STRING, number=1) + + expiration_time_usec = proto.Field(proto.INT64, number=2) + + fingerprint = proto.Field(proto.STRING, number=3) + + name = proto.Field(proto.STRING, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/oslogin_v1/gapic/enums.py b/google/cloud/oslogin_v1/gapic/enums.py deleted file mode 100644 index 48c48da..0000000 --- a/google/cloud/oslogin_v1/gapic/enums.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class OperatingSystemType(enum.IntEnum): - """ - The operating system options for account entries. - - Attributes: - OPERATING_SYSTEM_TYPE_UNSPECIFIED (int): The operating system type associated with the user account information is - unspecified. - LINUX (int): Linux user account information. - WINDOWS (int): Windows user account information. - """ - - OPERATING_SYSTEM_TYPE_UNSPECIFIED = 0 - LINUX = 1 - WINDOWS = 2 diff --git a/google/cloud/oslogin_v1/gapic/os_login_service_client.py b/google/cloud/oslogin_v1/gapic/os_login_service_client.py deleted file mode 100644 index 2f8e11e..0000000 --- a/google/cloud/oslogin_v1/gapic/os_login_service_client.py +++ /dev/null @@ -1,664 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.oslogin.v1 OsLoginService API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.path_template -import grpc - -from google.cloud.oslogin_v1.gapic import enums -from google.cloud.oslogin_v1.gapic import os_login_service_client_config -from google.cloud.oslogin_v1.gapic.transports import os_login_service_grpc_transport -from google.cloud.oslogin_v1.proto import common_pb2 -from google.cloud.oslogin_v1.proto import oslogin_pb2 -from google.cloud.oslogin_v1.proto import oslogin_pb2_grpc -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-os-login", -).version - - -class OsLoginServiceClient(object): - """ - Cloud OS Login API - - The Cloud OS Login API allows you to manage users and their associated SSH - public keys for logging into virtual machines on Google Cloud Platform. - """ - - SERVICE_ADDRESS = "oslogin.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.oslogin.v1.OsLoginService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - OsLoginServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def posix_account_path(cls, user, project): - """Return a fully-qualified posix_account string.""" - return google.api_core.path_template.expand( - "users/{user}/projects/{project}", user=user, project=project, - ) - - @classmethod - def ssh_public_key_path(cls, user, fingerprint): - """Return a fully-qualified ssh_public_key string.""" - return google.api_core.path_template.expand( - "users/{user}/sshPublicKeys/{fingerprint}", - user=user, - fingerprint=fingerprint, - ) - - @classmethod - def user_path(cls, user): - """Return a fully-qualified user string.""" - return google.api_core.path_template.expand("users/{user}", user=user,) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.OsLoginServiceGrpcTransport, - Callable[[~.Credentials, type], ~.OsLoginServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = os_login_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=os_login_service_grpc_transport.OsLoginServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = os_login_service_grpc_transport.OsLoginServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def delete_posix_account( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a POSIX account. - - Example: - >>> from google.cloud import oslogin_v1 - >>> - >>> client = oslogin_v1.OsLoginServiceClient() - >>> - >>> name = client.posix_account_path('[USER]', '[PROJECT]') - >>> - >>> client.delete_posix_account(name) - - Args: - name (str): Required. A reference to the POSIX account to update. POSIX accounts - are identified by the project ID they are associated with. A reference - to the POSIX account is in format ``users/{user}/projects/{project}``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_posix_account" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_posix_account" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_posix_account, - default_retry=self._method_configs["DeletePosixAccount"].retry, - default_timeout=self._method_configs["DeletePosixAccount"].timeout, - client_info=self._client_info, - ) - - request = oslogin_pb2.DeletePosixAccountRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_posix_account"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_ssh_public_key( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes an SSH public key. - - Example: - >>> from google.cloud import oslogin_v1 - >>> - >>> client = oslogin_v1.OsLoginServiceClient() - >>> - >>> name = client.ssh_public_key_path('[USER]', '[FINGERPRINT]') - >>> - >>> client.delete_ssh_public_key(name) - - Args: - name (str): Required. The fingerprint of the public key to update. Public keys - are identified by their SHA-256 fingerprint. The fingerprint of the - public key is in format ``users/{user}/sshPublicKeys/{fingerprint}``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_ssh_public_key" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_ssh_public_key" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_ssh_public_key, - default_retry=self._method_configs["DeleteSshPublicKey"].retry, - default_timeout=self._method_configs["DeleteSshPublicKey"].timeout, - client_info=self._client_info, - ) - - request = oslogin_pb2.DeleteSshPublicKeyRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_ssh_public_key"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_login_profile( - self, - name, - project_id=None, - system_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Retrieves the profile information used for logging in to a virtual machine - on Google Compute Engine. - - Example: - >>> from google.cloud import oslogin_v1 - >>> - >>> client = oslogin_v1.OsLoginServiceClient() - >>> - >>> name = client.user_path('[USER]') - >>> - >>> response = client.get_login_profile(name) - - Args: - name (str): Required. The unique ID for the user in format ``users/{user}``. - project_id (str): The project ID of the Google Cloud Platform project. - system_id (str): A system ID for filtering the results of the request. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.oslogin_v1.types.LoginProfile` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_login_profile" not in self._inner_api_calls: - self._inner_api_calls[ - "get_login_profile" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_login_profile, - default_retry=self._method_configs["GetLoginProfile"].retry, - default_timeout=self._method_configs["GetLoginProfile"].timeout, - client_info=self._client_info, - ) - - request = oslogin_pb2.GetLoginProfileRequest( - name=name, project_id=project_id, system_id=system_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_login_profile"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_ssh_public_key( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Retrieves an SSH public key. - - Example: - >>> from google.cloud import oslogin_v1 - >>> - >>> client = oslogin_v1.OsLoginServiceClient() - >>> - >>> name = client.ssh_public_key_path('[USER]', '[FINGERPRINT]') - >>> - >>> response = client.get_ssh_public_key(name) - - Args: - name (str): Required. The fingerprint of the public key to retrieve. Public keys - are identified by their SHA-256 fingerprint. The fingerprint of the - public key is in format ``users/{user}/sshPublicKeys/{fingerprint}``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.oslogin_v1.types.SshPublicKey` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_ssh_public_key" not in self._inner_api_calls: - self._inner_api_calls[ - "get_ssh_public_key" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_ssh_public_key, - default_retry=self._method_configs["GetSshPublicKey"].retry, - default_timeout=self._method_configs["GetSshPublicKey"].timeout, - client_info=self._client_info, - ) - - request = oslogin_pb2.GetSshPublicKeyRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_ssh_public_key"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def import_ssh_public_key( - self, - parent, - ssh_public_key=None, - project_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Adds an SSH public key and returns the profile information. Default POSIX - account information is set when no username and UID exist as part of the - login profile. - - Example: - >>> from google.cloud import oslogin_v1 - >>> - >>> client = oslogin_v1.OsLoginServiceClient() - >>> - >>> parent = client.user_path('[USER]') - >>> - >>> response = client.import_ssh_public_key(parent) - - Args: - parent (str): Required. The unique ID for the user in format ``users/{user}``. - ssh_public_key (Union[dict, ~google.cloud.oslogin_v1.types.SshPublicKey]): Optional. The SSH public key and expiration time. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.oslogin_v1.types.SshPublicKey` - project_id (str): The project ID of the Google Cloud Platform project. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.oslogin_v1.types.ImportSshPublicKeyResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "import_ssh_public_key" not in self._inner_api_calls: - self._inner_api_calls[ - "import_ssh_public_key" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.import_ssh_public_key, - default_retry=self._method_configs["ImportSshPublicKey"].retry, - default_timeout=self._method_configs["ImportSshPublicKey"].timeout, - client_info=self._client_info, - ) - - request = oslogin_pb2.ImportSshPublicKeyRequest( - parent=parent, ssh_public_key=ssh_public_key, project_id=project_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["import_ssh_public_key"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_ssh_public_key( - self, - name, - ssh_public_key, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates an SSH public key and returns the profile information. This method - supports patch semantics. - - Example: - >>> from google.cloud import oslogin_v1 - >>> - >>> client = oslogin_v1.OsLoginServiceClient() - >>> - >>> name = client.ssh_public_key_path('[USER]', '[FINGERPRINT]') - >>> - >>> # TODO: Initialize `ssh_public_key`: - >>> ssh_public_key = {} - >>> - >>> response = client.update_ssh_public_key(name, ssh_public_key) - - Args: - name (str): Required. The fingerprint of the public key to update. Public keys - are identified by their SHA-256 fingerprint. The fingerprint of the - public key is in format ``users/{user}/sshPublicKeys/{fingerprint}``. - ssh_public_key (Union[dict, ~google.cloud.oslogin_v1.types.SshPublicKey]): Required. The SSH public key and expiration time. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.oslogin_v1.types.SshPublicKey` - update_mask (Union[dict, ~google.cloud.oslogin_v1.types.FieldMask]): Mask to control which fields get updated. Updates all if not present. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.oslogin_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.oslogin_v1.types.SshPublicKey` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_ssh_public_key" not in self._inner_api_calls: - self._inner_api_calls[ - "update_ssh_public_key" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_ssh_public_key, - default_retry=self._method_configs["UpdateSshPublicKey"].retry, - default_timeout=self._method_configs["UpdateSshPublicKey"].timeout, - client_info=self._client_info, - ) - - request = oslogin_pb2.UpdateSshPublicKeyRequest( - name=name, ssh_public_key=ssh_public_key, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_ssh_public_key"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/oslogin_v1/gapic/os_login_service_client_config.py b/google/cloud/oslogin_v1/gapic/os_login_service_client_config.py deleted file mode 100644 index cc3bb69..0000000 --- a/google/cloud/oslogin_v1/gapic/os_login_service_client_config.py +++ /dev/null @@ -1,62 +0,0 @@ -config = { - "interfaces": { - "google.cloud.oslogin.v1.OsLoginService": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 10000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 10000, - "total_timeout_millis": 10000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "DeletePosixAccount": { - "timeout_millis": 10000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "DeleteSshPublicKey": { - "timeout_millis": 10000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetLoginProfile": { - "timeout_millis": 10000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetSshPublicKey": { - "timeout_millis": 10000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "ImportSshPublicKey": { - "timeout_millis": 10000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "UpdateSshPublicKey": { - "timeout_millis": 10000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/oslogin_v1/gapic/transports/__init__.py b/google/cloud/oslogin_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/oslogin_v1/gapic/transports/os_login_service_grpc_transport.py b/google/cloud/oslogin_v1/gapic/transports/os_login_service_grpc_transport.py deleted file mode 100644 index 1ee7295..0000000 --- a/google/cloud/oslogin_v1/gapic/transports/os_login_service_grpc_transport.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.oslogin_v1.proto import oslogin_pb2_grpc - - -class OsLoginServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.oslogin.v1 OsLoginService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/compute", - ) - - def __init__( - self, channel=None, credentials=None, address="oslogin.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "os_login_service_stub": oslogin_pb2_grpc.OsLoginServiceStub(channel), - } - - @classmethod - def create_channel( - cls, address="oslogin.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def delete_posix_account(self): - """Return the gRPC stub for :meth:`OsLoginServiceClient.delete_posix_account`. - - Deletes a POSIX account. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["os_login_service_stub"].DeletePosixAccount - - @property - def delete_ssh_public_key(self): - """Return the gRPC stub for :meth:`OsLoginServiceClient.delete_ssh_public_key`. - - Deletes an SSH public key. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["os_login_service_stub"].DeleteSshPublicKey - - @property - def get_login_profile(self): - """Return the gRPC stub for :meth:`OsLoginServiceClient.get_login_profile`. - - Retrieves the profile information used for logging in to a virtual machine - on Google Compute Engine. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["os_login_service_stub"].GetLoginProfile - - @property - def get_ssh_public_key(self): - """Return the gRPC stub for :meth:`OsLoginServiceClient.get_ssh_public_key`. - - Retrieves an SSH public key. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["os_login_service_stub"].GetSshPublicKey - - @property - def import_ssh_public_key(self): - """Return the gRPC stub for :meth:`OsLoginServiceClient.import_ssh_public_key`. - - Adds an SSH public key and returns the profile information. Default POSIX - account information is set when no username and UID exist as part of the - login profile. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["os_login_service_stub"].ImportSshPublicKey - - @property - def update_ssh_public_key(self): - """Return the gRPC stub for :meth:`OsLoginServiceClient.update_ssh_public_key`. - - Updates an SSH public key and returns the profile information. This method - supports patch semantics. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["os_login_service_stub"].UpdateSshPublicKey diff --git a/google/cloud/oslogin_v1/proto/__init__.py b/google/cloud/oslogin_v1/proto/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/oslogin_v1/proto/common_pb2.py b/google/cloud/oslogin_v1/proto/common_pb2.py deleted file mode 100644 index cfc12d1..0000000 --- a/google/cloud/oslogin_v1/proto/common_pb2.py +++ /dev/null @@ -1,481 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/oslogin/common/common.proto - -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/oslogin/common/common.proto", - package="google.cloud.oslogin.common", - syntax="proto3", - serialized_options=b"\n\037com.google.cloud.oslogin.commonB\014OsLoginProtoZAgoogle.golang.org/genproto/googleapis/cloud/oslogin/common;common\252\002\033Google.Cloud.OsLogin.Common\312\002\033Google\\Cloud\\OsLogin\\Common\352\002\036Google::Cloud::OsLogin::Common\352A+\n\033oslogin.googleapis.com/User\022\014users/{user}", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n(google/cloud/oslogin/common/common.proto\x12\x1bgoogle.cloud.oslogin.common\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto"\xdc\x02\n\x0cPosixAccount\x12\x0f\n\x07primary\x18\x01 \x01(\x08\x12\x10\n\x08username\x18\x02 \x01(\t\x12\x0b\n\x03uid\x18\x03 \x01(\x03\x12\x0b\n\x03gid\x18\x04 \x01(\x03\x12\x16\n\x0ehome_directory\x18\x05 \x01(\t\x12\r\n\x05shell\x18\x06 \x01(\t\x12\r\n\x05gecos\x18\x07 \x01(\t\x12\x11\n\tsystem_id\x18\x08 \x01(\t\x12\x17\n\naccount_id\x18\t \x01(\tB\x03\xe0\x41\x03\x12O\n\x15operating_system_type\x18\n \x01(\x0e\x32\x30.google.cloud.oslogin.common.OperatingSystemType\x12\x11\n\x04name\x18\x0b \x01(\tB\x03\xe0\x41\x03:I\xea\x41\x46\n#oslogin.googleapis.com/PosixAccount\x12\x1fusers/{user}/projects/{project}"\xba\x01\n\x0cSshPublicKey\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x1c\n\x14\x65xpiration_time_usec\x18\x02 \x01(\x03\x12\x18\n\x0b\x66ingerprint\x18\x03 \x01(\tB\x03\xe0\x41\x03\x12\x11\n\x04name\x18\x04 \x01(\tB\x03\xe0\x41\x03:R\xea\x41O\n#oslogin.googleapis.com/SshPublicKey\x12(users/{user}/sshPublicKeys/{fingerprint}*T\n\x13OperatingSystemType\x12%\n!OPERATING_SYSTEM_TYPE_UNSPECIFIED\x10\x00\x12\t\n\x05LINUX\x10\x01\x12\x0b\n\x07WINDOWS\x10\x02\x42\xfd\x01\n\x1f\x63om.google.cloud.oslogin.commonB\x0cOsLoginProtoZAgoogle.golang.org/genproto/googleapis/cloud/oslogin/common;common\xaa\x02\x1bGoogle.Cloud.OsLogin.Common\xca\x02\x1bGoogle\\Cloud\\OsLogin\\Common\xea\x02\x1eGoogle::Cloud::OsLogin::Common\xea\x41+\n\x1boslogin.googleapis.com/User\x12\x0cusers/{user}b\x06proto3', - dependencies=[ - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - -_OPERATINGSYSTEMTYPE = _descriptor.EnumDescriptor( - name="OperatingSystemType", - full_name="google.cloud.oslogin.common.OperatingSystemType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="OPERATING_SYSTEM_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LINUX", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="WINDOWS", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=673, - serialized_end=757, -) -_sym_db.RegisterEnumDescriptor(_OPERATINGSYSTEMTYPE) - -OperatingSystemType = enum_type_wrapper.EnumTypeWrapper(_OPERATINGSYSTEMTYPE) -OPERATING_SYSTEM_TYPE_UNSPECIFIED = 0 -LINUX = 1 -WINDOWS = 2 - - -_POSIXACCOUNT = _descriptor.Descriptor( - name="PosixAccount", - full_name="google.cloud.oslogin.common.PosixAccount", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="primary", - full_name="google.cloud.oslogin.common.PosixAccount.primary", - index=0, - number=1, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="username", - full_name="google.cloud.oslogin.common.PosixAccount.username", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uid", - full_name="google.cloud.oslogin.common.PosixAccount.uid", - index=2, - number=3, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gid", - full_name="google.cloud.oslogin.common.PosixAccount.gid", - index=3, - number=4, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="home_directory", - full_name="google.cloud.oslogin.common.PosixAccount.home_directory", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="shell", - full_name="google.cloud.oslogin.common.PosixAccount.shell", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="gecos", - full_name="google.cloud.oslogin.common.PosixAccount.gecos", - index=6, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="system_id", - full_name="google.cloud.oslogin.common.PosixAccount.system_id", - index=7, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="account_id", - full_name="google.cloud.oslogin.common.PosixAccount.account_id", - index=8, - number=9, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="operating_system_type", - full_name="google.cloud.oslogin.common.PosixAccount.operating_system_type", - index=9, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.common.PosixAccount.name", - index=10, - number=11, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352AF\n#oslogin.googleapis.com/PosixAccount\022\037users/{user}/projects/{project}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=134, - serialized_end=482, -) - - -_SSHPUBLICKEY = _descriptor.Descriptor( - name="SshPublicKey", - full_name="google.cloud.oslogin.common.SshPublicKey", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.oslogin.common.SshPublicKey.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="expiration_time_usec", - full_name="google.cloud.oslogin.common.SshPublicKey.expiration_time_usec", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="fingerprint", - full_name="google.cloud.oslogin.common.SshPublicKey.fingerprint", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.common.SshPublicKey.name", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352AO\n#oslogin.googleapis.com/SshPublicKey\022(users/{user}/sshPublicKeys/{fingerprint}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=485, - serialized_end=671, -) - -_POSIXACCOUNT.fields_by_name["operating_system_type"].enum_type = _OPERATINGSYSTEMTYPE -DESCRIPTOR.message_types_by_name["PosixAccount"] = _POSIXACCOUNT -DESCRIPTOR.message_types_by_name["SshPublicKey"] = _SSHPUBLICKEY -DESCRIPTOR.enum_types_by_name["OperatingSystemType"] = _OPERATINGSYSTEMTYPE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -PosixAccount = _reflection.GeneratedProtocolMessageType( - "PosixAccount", - (_message.Message,), - { - "DESCRIPTOR": _POSIXACCOUNT, - "__module__": "google.cloud.oslogin.common.common_pb2", - "__doc__": """The POSIX account information associated with a Google account. - - Attributes: - primary: - Only one POSIX account can be marked as primary. - username: - The username of the POSIX account. - uid: - The user ID. - gid: - The default group ID. - home_directory: - The path to the home directory for this account. - shell: - The path to the logic shell for this account. - gecos: - The GECOS (user information) entry for this account. - system_id: - System identifier for which account the username or uid - applies to. By default, the empty value is used. - account_id: - Output only. A POSIX account identifier. - operating_system_type: - The operating system type where this account applies. - name: - Output only. The canonical resource name. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.common.PosixAccount) - }, -) -_sym_db.RegisterMessage(PosixAccount) - -SshPublicKey = _reflection.GeneratedProtocolMessageType( - "SshPublicKey", - (_message.Message,), - { - "DESCRIPTOR": _SSHPUBLICKEY, - "__module__": "google.cloud.oslogin.common.common_pb2", - "__doc__": """The SSH public key information associated with a Google account. - - Attributes: - key: - Public key text in SSH format, defined by RFC4253 section 6.6. - expiration_time_usec: - An expiration time in microseconds since epoch. - fingerprint: - Output only. The SHA-256 fingerprint of the SSH public key. - name: - Output only. The canonical resource name. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.common.SshPublicKey) - }, -) -_sym_db.RegisterMessage(SshPublicKey) - - -DESCRIPTOR._options = None -_POSIXACCOUNT.fields_by_name["account_id"]._options = None -_POSIXACCOUNT.fields_by_name["name"]._options = None -_POSIXACCOUNT._options = None -_SSHPUBLICKEY.fields_by_name["fingerprint"]._options = None -_SSHPUBLICKEY.fields_by_name["name"]._options = None -_SSHPUBLICKEY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/oslogin_v1/proto/common_pb2_grpc.py b/google/cloud/oslogin_v1/proto/common_pb2_grpc.py deleted file mode 100644 index 07cb78f..0000000 --- a/google/cloud/oslogin_v1/proto/common_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/oslogin_v1/proto/oslogin_pb2.py b/google/cloud/oslogin_v1/proto/oslogin_pb2.py deleted file mode 100644 index 845a422..0000000 --- a/google/cloud/oslogin_v1/proto/oslogin_pb2.py +++ /dev/null @@ -1,892 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/oslogin_v1/proto/oslogin.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.oslogin_v1.proto import ( - common_pb2 as google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/oslogin_v1/proto/oslogin.proto", - package="google.cloud.oslogin.v1", - syntax="proto3", - serialized_options=b"\n\033com.google.cloud.oslogin.v1B\014OsLoginProtoP\001Z>google.golang.org/genproto/googleapis/cloud/oslogin/v1;oslogin\252\002\027Google.Cloud.OsLogin.V1\312\002\027Google\\Cloud\\OsLogin\\V1\352\002\032Google::Cloud::OsLogin::V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n+google/cloud/oslogin_v1/proto/oslogin.proto\x12\x17google.cloud.oslogin.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a(google/cloud/oslogin/common/common.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto"\x98\x02\n\x0cLoginProfile\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x41\n\x0eposix_accounts\x18\x02 \x03(\x0b\x32).google.cloud.oslogin.common.PosixAccount\x12Q\n\x0fssh_public_keys\x18\x03 \x03(\x0b\x32\x38.google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry\x1a_\n\x12SshPublicKeysEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x01(\x0b\x32).google.cloud.oslogin.common.SshPublicKey:\x02\x38\x01"V\n\x19\x44\x65letePosixAccountRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/PosixAccount"V\n\x19\x44\x65leteSshPublicKeyRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/SshPublicKey"z\n\x16GetLoginProfileRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\x12#oslogin.googleapis.com/PosixAccount\x12\x12\n\nproject_id\x18\x02 \x01(\t\x12\x11\n\tsystem_id\x18\x03 \x01(\t"S\n\x16GetSshPublicKeyRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/SshPublicKey"\xb4\x01\n\x19ImportSshPublicKeyRequest\x12;\n\x06parent\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\x12#oslogin.googleapis.com/SshPublicKey\x12\x46\n\x0essh_public_key\x18\x02 \x01(\x0b\x32).google.cloud.oslogin.common.SshPublicKeyB\x03\xe0\x41\x01\x12\x12\n\nproject_id\x18\x03 \x01(\t"Z\n\x1aImportSshPublicKeyResponse\x12<\n\rlogin_profile\x18\x01 \x01(\x0b\x32%.google.cloud.oslogin.v1.LoginProfile"\xcf\x01\n\x19UpdateSshPublicKeyRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/SshPublicKey\x12\x46\n\x0essh_public_key\x18\x02 \x01(\x0b\x32).google.cloud.oslogin.common.SshPublicKeyB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.FieldMask2\xd0\t\n\x0eOsLoginService\x12\x8e\x01\n\x12\x44\x65letePosixAccount\x12\x32.google.cloud.oslogin.v1.DeletePosixAccountRequest\x1a\x16.google.protobuf.Empty",\x82\xd3\xe4\x93\x02\x1f*\x1d/v1/{name=users/*/projects/*}\xda\x41\x04name\x12\x93\x01\n\x12\x44\x65leteSshPublicKey\x12\x32.google.cloud.oslogin.v1.DeleteSshPublicKeyRequest\x1a\x16.google.protobuf.Empty"1\x82\xd3\xe4\x93\x02$*"/v1/{name=users/*/sshPublicKeys/*}\xda\x41\x04name\x12\x99\x01\n\x0fGetLoginProfile\x12/.google.cloud.oslogin.v1.GetLoginProfileRequest\x1a%.google.cloud.oslogin.v1.LoginProfile".\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{name=users/*}/loginProfile\xda\x41\x04name\x12\xa0\x01\n\x0fGetSshPublicKey\x12/.google.cloud.oslogin.v1.GetSshPublicKeyRequest\x1a).google.cloud.oslogin.common.SshPublicKey"1\x82\xd3\xe4\x93\x02$\x12"/v1/{name=users/*/sshPublicKeys/*}\xda\x41\x04name\x12\xf9\x01\n\x12ImportSshPublicKey\x12\x32.google.cloud.oslogin.v1.ImportSshPublicKeyRequest\x1a\x33.google.cloud.oslogin.v1.ImportSshPublicKeyResponse"z\x82\xd3\xe4\x93\x02\x39"\'/v1/{parent=users/*}:importSshPublicKey:\x0essh_public_key\xda\x41\x15parent,ssh_public_key\xda\x41 parent,ssh_public_key,project_id\x12\xe7\x01\n\x12UpdateSshPublicKey\x12\x32.google.cloud.oslogin.v1.UpdateSshPublicKeyRequest\x1a).google.cloud.oslogin.common.SshPublicKey"r\x82\xd3\xe4\x93\x02\x34\x32"/v1/{name=users/*/sshPublicKeys/*}:\x0essh_public_key\xda\x41\x13name,ssh_public_key\xda\x41\x1fname,ssh_public_key,update_mask\x1ar\xca\x41\x16oslogin.googleapis.com\xd2\x41Vhttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/computeB\xbe\x01\n\x1b\x63om.google.cloud.oslogin.v1B\x0cOsLoginProtoP\x01Z>google.golang.org/genproto/googleapis/cloud/oslogin/v1;oslogin\xaa\x02\x17Google.Cloud.OsLogin.V1\xca\x02\x17Google\\Cloud\\OsLogin\\V1\xea\x02\x1aGoogle::Cloud::OsLogin::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - ], -) - - -_LOGINPROFILE_SSHPUBLICKEYSENTRY = _descriptor.Descriptor( - name="SshPublicKeysEntry", - full_name="google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=478, - serialized_end=573, -) - -_LOGINPROFILE = _descriptor.Descriptor( - name="LoginProfile", - full_name="google.cloud.oslogin.v1.LoginProfile", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.v1.LoginProfile.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="posix_accounts", - full_name="google.cloud.oslogin.v1.LoginProfile.posix_accounts", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ssh_public_keys", - full_name="google.cloud.oslogin.v1.LoginProfile.ssh_public_keys", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LOGINPROFILE_SSHPUBLICKEYSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=293, - serialized_end=573, -) - - -_DELETEPOSIXACCOUNTREQUEST = _descriptor.Descriptor( - name="DeletePosixAccountRequest", - full_name="google.cloud.oslogin.v1.DeletePosixAccountRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.v1.DeletePosixAccountRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/PosixAccount", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=575, - serialized_end=661, -) - - -_DELETESSHPUBLICKEYREQUEST = _descriptor.Descriptor( - name="DeleteSshPublicKeyRequest", - full_name="google.cloud.oslogin.v1.DeleteSshPublicKeyRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.v1.DeleteSshPublicKeyRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/SshPublicKey", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=663, - serialized_end=749, -) - - -_GETLOGINPROFILEREQUEST = _descriptor.Descriptor( - name="GetLoginProfileRequest", - full_name="google.cloud.oslogin.v1.GetLoginProfileRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.v1.GetLoginProfileRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\022#oslogin.googleapis.com/PosixAccount", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_id", - full_name="google.cloud.oslogin.v1.GetLoginProfileRequest.project_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="system_id", - full_name="google.cloud.oslogin.v1.GetLoginProfileRequest.system_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=751, - serialized_end=873, -) - - -_GETSSHPUBLICKEYREQUEST = _descriptor.Descriptor( - name="GetSshPublicKeyRequest", - full_name="google.cloud.oslogin.v1.GetSshPublicKeyRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.v1.GetSshPublicKeyRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/SshPublicKey", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=875, - serialized_end=958, -) - - -_IMPORTSSHPUBLICKEYREQUEST = _descriptor.Descriptor( - name="ImportSshPublicKeyRequest", - full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\022#oslogin.googleapis.com/SshPublicKey", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ssh_public_key", - full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest.ssh_public_key", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_id", - full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest.project_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=961, - serialized_end=1141, -) - - -_IMPORTSSHPUBLICKEYRESPONSE = _descriptor.Descriptor( - name="ImportSshPublicKeyResponse", - full_name="google.cloud.oslogin.v1.ImportSshPublicKeyResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="login_profile", - full_name="google.cloud.oslogin.v1.ImportSshPublicKeyResponse.login_profile", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1143, - serialized_end=1233, -) - - -_UPDATESSHPUBLICKEYREQUEST = _descriptor.Descriptor( - name="UpdateSshPublicKeyRequest", - full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/SshPublicKey", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ssh_public_key", - full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest.ssh_public_key", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest.update_mask", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1236, - serialized_end=1443, -) - -_LOGINPROFILE_SSHPUBLICKEYSENTRY.fields_by_name[ - "value" -].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY -_LOGINPROFILE_SSHPUBLICKEYSENTRY.containing_type = _LOGINPROFILE -_LOGINPROFILE.fields_by_name[ - "posix_accounts" -].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._POSIXACCOUNT -_LOGINPROFILE.fields_by_name[ - "ssh_public_keys" -].message_type = _LOGINPROFILE_SSHPUBLICKEYSENTRY -_IMPORTSSHPUBLICKEYREQUEST.fields_by_name[ - "ssh_public_key" -].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY -_IMPORTSSHPUBLICKEYRESPONSE.fields_by_name["login_profile"].message_type = _LOGINPROFILE -_UPDATESSHPUBLICKEYREQUEST.fields_by_name[ - "ssh_public_key" -].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY -_UPDATESSHPUBLICKEYREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -DESCRIPTOR.message_types_by_name["LoginProfile"] = _LOGINPROFILE -DESCRIPTOR.message_types_by_name[ - "DeletePosixAccountRequest" -] = _DELETEPOSIXACCOUNTREQUEST -DESCRIPTOR.message_types_by_name[ - "DeleteSshPublicKeyRequest" -] = _DELETESSHPUBLICKEYREQUEST -DESCRIPTOR.message_types_by_name["GetLoginProfileRequest"] = _GETLOGINPROFILEREQUEST -DESCRIPTOR.message_types_by_name["GetSshPublicKeyRequest"] = _GETSSHPUBLICKEYREQUEST -DESCRIPTOR.message_types_by_name[ - "ImportSshPublicKeyRequest" -] = _IMPORTSSHPUBLICKEYREQUEST -DESCRIPTOR.message_types_by_name[ - "ImportSshPublicKeyResponse" -] = _IMPORTSSHPUBLICKEYRESPONSE -DESCRIPTOR.message_types_by_name[ - "UpdateSshPublicKeyRequest" -] = _UPDATESSHPUBLICKEYREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -LoginProfile = _reflection.GeneratedProtocolMessageType( - "LoginProfile", - (_message.Message,), - { - "SshPublicKeysEntry": _reflection.GeneratedProtocolMessageType( - "SshPublicKeysEntry", - (_message.Message,), - { - "DESCRIPTOR": _LOGINPROFILE_SSHPUBLICKEYSENTRY, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry) - }, - ), - "DESCRIPTOR": _LOGINPROFILE, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """The user profile information used for logging in to a virtual machine - on Google Compute Engine. - - Attributes: - name: - Required. A unique user ID. - posix_accounts: - The list of POSIX accounts associated with the user. - ssh_public_keys: - A map from SSH public key fingerprint to the associated key - object. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.LoginProfile) - }, -) -_sym_db.RegisterMessage(LoginProfile) -_sym_db.RegisterMessage(LoginProfile.SshPublicKeysEntry) - -DeletePosixAccountRequest = _reflection.GeneratedProtocolMessageType( - "DeletePosixAccountRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEPOSIXACCOUNTREQUEST, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A request message for deleting a POSIX account entry. - - Attributes: - name: - Required. A reference to the POSIX account to update. POSIX - accounts are identified by the project ID they are associated - with. A reference to the POSIX account is in format - ``users/{user}/projects/{project}``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.DeletePosixAccountRequest) - }, -) -_sym_db.RegisterMessage(DeletePosixAccountRequest) - -DeleteSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType( - "DeleteSshPublicKeyRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETESSHPUBLICKEYREQUEST, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A request message for deleting an SSH public key. - - Attributes: - name: - Required. The fingerprint of the public key to update. Public - keys are identified by their SHA-256 fingerprint. The - fingerprint of the public key is in format - ``users/{user}/sshPublicKeys/{fingerprint}``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.DeleteSshPublicKeyRequest) - }, -) -_sym_db.RegisterMessage(DeleteSshPublicKeyRequest) - -GetLoginProfileRequest = _reflection.GeneratedProtocolMessageType( - "GetLoginProfileRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETLOGINPROFILEREQUEST, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A request message for retrieving the login profile information for a - user. - - Attributes: - name: - Required. The unique ID for the user in format - ``users/{user}``. - project_id: - The project ID of the Google Cloud Platform project. - system_id: - A system ID for filtering the results of the request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.GetLoginProfileRequest) - }, -) -_sym_db.RegisterMessage(GetLoginProfileRequest) - -GetSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType( - "GetSshPublicKeyRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSSHPUBLICKEYREQUEST, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A request message for retrieving an SSH public key. - - Attributes: - name: - Required. The fingerprint of the public key to retrieve. - Public keys are identified by their SHA-256 fingerprint. The - fingerprint of the public key is in format - ``users/{user}/sshPublicKeys/{fingerprint}``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.GetSshPublicKeyRequest) - }, -) -_sym_db.RegisterMessage(GetSshPublicKeyRequest) - -ImportSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType( - "ImportSshPublicKeyRequest", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTSSHPUBLICKEYREQUEST, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A request message for importing an SSH public key. - - Attributes: - parent: - Required. The unique ID for the user in format - ``users/{user}``. - ssh_public_key: - Optional. The SSH public key and expiration time. - project_id: - The project ID of the Google Cloud Platform project. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.ImportSshPublicKeyRequest) - }, -) -_sym_db.RegisterMessage(ImportSshPublicKeyRequest) - -ImportSshPublicKeyResponse = _reflection.GeneratedProtocolMessageType( - "ImportSshPublicKeyResponse", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTSSHPUBLICKEYRESPONSE, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A response message for importing an SSH public key. - - Attributes: - login_profile: - The login profile information for the user. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.ImportSshPublicKeyResponse) - }, -) -_sym_db.RegisterMessage(ImportSshPublicKeyResponse) - -UpdateSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSshPublicKeyRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESSHPUBLICKEYREQUEST, - "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2", - "__doc__": """A request message for updating an SSH public key. - - Attributes: - name: - Required. The fingerprint of the public key to update. Public - keys are identified by their SHA-256 fingerprint. The - fingerprint of the public key is in format - ``users/{user}/sshPublicKeys/{fingerprint}``. - ssh_public_key: - Required. The SSH public key and expiration time. - update_mask: - Mask to control which fields get updated. Updates all if not - present. - """, - # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.UpdateSshPublicKeyRequest) - }, -) -_sym_db.RegisterMessage(UpdateSshPublicKeyRequest) - - -DESCRIPTOR._options = None -_LOGINPROFILE_SSHPUBLICKEYSENTRY._options = None -_LOGINPROFILE.fields_by_name["name"]._options = None -_DELETEPOSIXACCOUNTREQUEST.fields_by_name["name"]._options = None -_DELETESSHPUBLICKEYREQUEST.fields_by_name["name"]._options = None -_GETLOGINPROFILEREQUEST.fields_by_name["name"]._options = None -_GETSSHPUBLICKEYREQUEST.fields_by_name["name"]._options = None -_IMPORTSSHPUBLICKEYREQUEST.fields_by_name["parent"]._options = None -_IMPORTSSHPUBLICKEYREQUEST.fields_by_name["ssh_public_key"]._options = None -_UPDATESSHPUBLICKEYREQUEST.fields_by_name["name"]._options = None -_UPDATESSHPUBLICKEYREQUEST.fields_by_name["ssh_public_key"]._options = None - -_OSLOGINSERVICE = _descriptor.ServiceDescriptor( - name="OsLoginService", - full_name="google.cloud.oslogin.v1.OsLoginService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\026oslogin.googleapis.com\322AVhttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/compute", - create_key=_descriptor._internal_create_key, - serialized_start=1446, - serialized_end=2678, - methods=[ - _descriptor.MethodDescriptor( - name="DeletePosixAccount", - full_name="google.cloud.oslogin.v1.OsLoginService.DeletePosixAccount", - index=0, - containing_service=None, - input_type=_DELETEPOSIXACCOUNTREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002\037*\035/v1/{name=users/*/projects/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteSshPublicKey", - full_name="google.cloud.oslogin.v1.OsLoginService.DeleteSshPublicKey", - index=1, - containing_service=None, - input_type=_DELETESSHPUBLICKEYREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002$*"/v1/{name=users/*/sshPublicKeys/*}\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetLoginProfile", - full_name="google.cloud.oslogin.v1.OsLoginService.GetLoginProfile", - index=2, - containing_service=None, - input_type=_GETLOGINPROFILEREQUEST, - output_type=_LOGINPROFILE, - serialized_options=b"\202\323\344\223\002!\022\037/v1/{name=users/*}/loginProfile\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSshPublicKey", - full_name="google.cloud.oslogin.v1.OsLoginService.GetSshPublicKey", - index=3, - containing_service=None, - input_type=_GETSSHPUBLICKEYREQUEST, - output_type=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY, - serialized_options=b'\202\323\344\223\002$\022"/v1/{name=users/*/sshPublicKeys/*}\332A\004name', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ImportSshPublicKey", - full_name="google.cloud.oslogin.v1.OsLoginService.ImportSshPublicKey", - index=4, - containing_service=None, - input_type=_IMPORTSSHPUBLICKEYREQUEST, - output_type=_IMPORTSSHPUBLICKEYRESPONSE, - serialized_options=b"\202\323\344\223\0029\"'/v1/{parent=users/*}:importSshPublicKey:\016ssh_public_key\332A\025parent,ssh_public_key\332A parent,ssh_public_key,project_id", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSshPublicKey", - full_name="google.cloud.oslogin.v1.OsLoginService.UpdateSshPublicKey", - index=5, - containing_service=None, - input_type=_UPDATESSHPUBLICKEYREQUEST, - output_type=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY, - serialized_options=b'\202\323\344\223\00242"/v1/{name=users/*/sshPublicKeys/*}:\016ssh_public_key\332A\023name,ssh_public_key\332A\037name,ssh_public_key,update_mask', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_OSLOGINSERVICE) - -DESCRIPTOR.services_by_name["OsLoginService"] = _OSLOGINSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py b/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py deleted file mode 100644 index 6b00266..0000000 --- a/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py +++ /dev/null @@ -1,148 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -from google.cloud.oslogin_v1.proto import ( - common_pb2 as google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2, -) -from google.cloud.oslogin_v1.proto import ( - oslogin_pb2 as google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class OsLoginServiceStub(object): - """Cloud OS Login API - - The Cloud OS Login API allows you to manage users and their associated SSH - public keys for logging into virtual machines on Google Cloud Platform. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.DeletePosixAccount = channel.unary_unary( - "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount", - request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeletePosixAccountRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.DeleteSshPublicKey = channel.unary_unary( - "/google.cloud.oslogin.v1.OsLoginService/DeleteSshPublicKey", - request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeleteSshPublicKeyRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.GetLoginProfile = channel.unary_unary( - "/google.cloud.oslogin.v1.OsLoginService/GetLoginProfile", - request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetLoginProfileRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.LoginProfile.FromString, - ) - self.GetSshPublicKey = channel.unary_unary( - "/google.cloud.oslogin.v1.OsLoginService/GetSshPublicKey", - request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetSshPublicKeyRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.FromString, - ) - self.ImportSshPublicKey = channel.unary_unary( - "/google.cloud.oslogin.v1.OsLoginService/ImportSshPublicKey", - request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyResponse.FromString, - ) - self.UpdateSshPublicKey = channel.unary_unary( - "/google.cloud.oslogin.v1.OsLoginService/UpdateSshPublicKey", - request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.UpdateSshPublicKeyRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.FromString, - ) - - -class OsLoginServiceServicer(object): - """Cloud OS Login API - - The Cloud OS Login API allows you to manage users and their associated SSH - public keys for logging into virtual machines on Google Cloud Platform. - """ - - def DeletePosixAccount(self, request, context): - """Deletes a POSIX account. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteSshPublicKey(self, request, context): - """Deletes an SSH public key. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetLoginProfile(self, request, context): - """Retrieves the profile information used for logging in to a virtual machine - on Google Compute Engine. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSshPublicKey(self, request, context): - """Retrieves an SSH public key. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ImportSshPublicKey(self, request, context): - """Adds an SSH public key and returns the profile information. Default POSIX - account information is set when no username and UID exist as part of the - login profile. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSshPublicKey(self, request, context): - """Updates an SSH public key and returns the profile information. This method - supports patch semantics. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_OsLoginServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "DeletePosixAccount": grpc.unary_unary_rpc_method_handler( - servicer.DeletePosixAccount, - request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeletePosixAccountRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "DeleteSshPublicKey": grpc.unary_unary_rpc_method_handler( - servicer.DeleteSshPublicKey, - request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeleteSshPublicKeyRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "GetLoginProfile": grpc.unary_unary_rpc_method_handler( - servicer.GetLoginProfile, - request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetLoginProfileRequest.FromString, - response_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.LoginProfile.SerializeToString, - ), - "GetSshPublicKey": grpc.unary_unary_rpc_method_handler( - servicer.GetSshPublicKey, - request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetSshPublicKeyRequest.FromString, - response_serializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.SerializeToString, - ), - "ImportSshPublicKey": grpc.unary_unary_rpc_method_handler( - servicer.ImportSshPublicKey, - request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyRequest.FromString, - response_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyResponse.SerializeToString, - ), - "UpdateSshPublicKey": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSshPublicKey, - request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.UpdateSshPublicKeyRequest.FromString, - response_serializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.oslogin.v1.OsLoginService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/google/cloud/oslogin_v1/py.typed b/google/cloud/oslogin_v1/py.typed new file mode 100644 index 0000000..825d05f --- /dev/null +++ b/google/cloud/oslogin_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-oslogin package uses inline types. diff --git a/google/cloud/oslogin_v1/services/__init__.py b/google/cloud/oslogin_v1/services/__init__.py new file mode 100644 index 0000000..42ffdf2 --- /dev/null +++ b/google/cloud/oslogin_v1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/__init__.py b/google/cloud/oslogin_v1/services/os_login_service/__init__.py similarity index 71% rename from google/cloud/__init__.py rename to google/cloud/oslogin_v1/services/os_login_service/__init__.py index 9a1b64a..4e7ce22 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/oslogin_v1/services/os_login_service/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import OsLoginServiceClient +from .async_client import OsLoginServiceAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "OsLoginServiceClient", + "OsLoginServiceAsyncClient", +) diff --git a/google/cloud/oslogin_v1/services/os_login_service/async_client.py b/google/cloud/oslogin_v1/services/os_login_service/async_client.py new file mode 100644 index 0000000..8afce3a --- /dev/null +++ b/google/cloud/oslogin_v1/services/os_login_service/async_client.py @@ -0,0 +1,631 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.oslogin_v1 import common # type: ignore +from google.cloud.oslogin_v1.types import oslogin +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OsLoginServiceGrpcAsyncIOTransport +from .client import OsLoginServiceClient + + +class OsLoginServiceAsyncClient: + """Cloud OS Login API + The Cloud OS Login API allows you to manage users and their + associated SSH public keys for logging into virtual machines on + Google Cloud Platform. + """ + + _client: OsLoginServiceClient + + DEFAULT_ENDPOINT = OsLoginServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OsLoginServiceClient.DEFAULT_MTLS_ENDPOINT + + ssh_public_key_path = staticmethod(OsLoginServiceClient.ssh_public_key_path) + parse_ssh_public_key_path = staticmethod( + OsLoginServiceClient.parse_ssh_public_key_path + ) + + from_service_account_file = OsLoginServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(OsLoginServiceClient).get_transport_class, type(OsLoginServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, OsLoginServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the os login service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.OsLoginServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = OsLoginServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def delete_posix_account( + self, + request: oslogin.DeletePosixAccountRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a POSIX account. + + Args: + request (:class:`~.oslogin.DeletePosixAccountRequest`): + The request object. A request message for deleting a + POSIX account entry. + name (:class:`str`): + Required. A reference to the POSIX account to update. + POSIX accounts are identified by the project ID they are + associated with. A reference to the POSIX account is in + format ``users/{user}/projects/{project}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = oslogin.DeletePosixAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_posix_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def delete_ssh_public_key( + self, + request: oslogin.DeleteSshPublicKeyRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an SSH public key. + + Args: + request (:class:`~.oslogin.DeleteSshPublicKeyRequest`): + The request object. A request message for deleting an + SSH public key. + name (:class:`str`): + Required. The fingerprint of the public key to update. + Public keys are identified by their SHA-256 fingerprint. + The fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = oslogin.DeleteSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_login_profile( + self, + request: oslogin.GetLoginProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> oslogin.LoginProfile: + r"""Retrieves the profile information used for logging in + to a virtual machine on Google Compute Engine. + + Args: + request (:class:`~.oslogin.GetLoginProfileRequest`): + The request object. A request message for retrieving the + login profile information for a user. + name (:class:`str`): + Required. The unique ID for the user in format + ``users/{user}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.oslogin.LoginProfile: + The user profile information used for + logging in to a virtual machine on + Google Compute Engine. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = oslogin.GetLoginProfileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_login_profile, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_ssh_public_key( + self, + request: oslogin.GetSshPublicKeyRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.SshPublicKey: + r"""Retrieves an SSH public key. + + Args: + request (:class:`~.oslogin.GetSshPublicKeyRequest`): + The request object. A request message for retrieving an + SSH public key. + name (:class:`str`): + Required. The fingerprint of the public key to retrieve. + Public keys are identified by their SHA-256 fingerprint. + The fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.SshPublicKey: + The SSH public key information + associated with a Google account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = oslogin.GetSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def import_ssh_public_key( + self, + request: oslogin.ImportSshPublicKeyRequest = None, + *, + parent: str = None, + ssh_public_key: common.SshPublicKey = None, + project_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> oslogin.ImportSshPublicKeyResponse: + r"""Adds an SSH public key and returns the profile + information. Default POSIX account information is set + when no username and UID exist as part of the login + profile. + + Args: + request (:class:`~.oslogin.ImportSshPublicKeyRequest`): + The request object. A request message for importing an + SSH public key. + parent (:class:`str`): + Required. The unique ID for the user in format + ``users/{user}``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ssh_public_key (:class:`~.common.SshPublicKey`): + Optional. The SSH public key and + expiration time. + This corresponds to the ``ssh_public_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + project_id (:class:`str`): + The project ID of the Google Cloud + Platform project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.oslogin.ImportSshPublicKeyResponse: + A response message for importing an + SSH public key. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, ssh_public_key, project_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = oslogin.ImportSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if ssh_public_key is not None: + request.ssh_public_key = ssh_public_key + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_ssh_public_key( + self, + request: oslogin.UpdateSshPublicKeyRequest = None, + *, + name: str = None, + ssh_public_key: common.SshPublicKey = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.SshPublicKey: + r"""Updates an SSH public key and returns the profile + information. This method supports patch semantics. + + Args: + request (:class:`~.oslogin.UpdateSshPublicKeyRequest`): + The request object. A request message for updating an + SSH public key. + name (:class:`str`): + Required. The fingerprint of the public key to update. + Public keys are identified by their SHA-256 fingerprint. + The fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ssh_public_key (:class:`~.common.SshPublicKey`): + Required. The SSH public key and + expiration time. + This corresponds to the ``ssh_public_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Mask to control which fields get + updated. Updates all if not present. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.SshPublicKey: + The SSH public key information + associated with a Google account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, ssh_public_key, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = oslogin.UpdateSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if ssh_public_key is not None: + request.ssh_public_key = ssh_public_key + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-os-login",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("OsLoginServiceAsyncClient",) diff --git a/google/cloud/oslogin_v1/services/os_login_service/client.py b/google/cloud/oslogin_v1/services/os_login_service/client.py new file mode 100644 index 0000000..ab59bfa --- /dev/null +++ b/google/cloud/oslogin_v1/services/os_login_service/client.py @@ -0,0 +1,751 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.oslogin_v1 import common # type: ignore +from google.cloud.oslogin_v1.types import oslogin +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OsLoginServiceGrpcTransport +from .transports.grpc_asyncio import OsLoginServiceGrpcAsyncIOTransport + + +class OsLoginServiceClientMeta(type): + """Metaclass for the OsLoginService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[OsLoginServiceTransport]] + _transport_registry["grpc"] = OsLoginServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OsLoginServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[OsLoginServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class OsLoginServiceClient(metaclass=OsLoginServiceClientMeta): + """Cloud OS Login API + The Cloud OS Login API allows you to manage users and their + associated SSH public keys for logging into virtual machines on + Google Cloud Platform. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "oslogin.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def ssh_public_key_path(user: str, fingerprint: str,) -> str: + """Return a fully-qualified ssh_public_key string.""" + return "users/{user}/sshPublicKeys/{fingerprint}".format( + user=user, fingerprint=fingerprint, + ) + + @staticmethod + def parse_ssh_public_key_path(path: str) -> Dict[str, str]: + """Parse a ssh_public_key path into its component segments.""" + m = re.match(r"^users/(?P.+?)/sshPublicKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, OsLoginServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the os login service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.OsLoginServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, OsLoginServiceTransport): + # transport is a OsLoginServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def delete_posix_account( + self, + request: oslogin.DeletePosixAccountRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a POSIX account. + + Args: + request (:class:`~.oslogin.DeletePosixAccountRequest`): + The request object. A request message for deleting a + POSIX account entry. + name (:class:`str`): + Required. A reference to the POSIX account to update. + POSIX accounts are identified by the project ID they are + associated with. A reference to the POSIX account is in + format ``users/{user}/projects/{project}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a oslogin.DeletePosixAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, oslogin.DeletePosixAccountRequest): + request = oslogin.DeletePosixAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_posix_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def delete_ssh_public_key( + self, + request: oslogin.DeleteSshPublicKeyRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an SSH public key. + + Args: + request (:class:`~.oslogin.DeleteSshPublicKeyRequest`): + The request object. A request message for deleting an + SSH public key. + name (:class:`str`): + Required. The fingerprint of the public key to update. + Public keys are identified by their SHA-256 fingerprint. + The fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a oslogin.DeleteSshPublicKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, oslogin.DeleteSshPublicKeyRequest): + request = oslogin.DeleteSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_ssh_public_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_login_profile( + self, + request: oslogin.GetLoginProfileRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> oslogin.LoginProfile: + r"""Retrieves the profile information used for logging in + to a virtual machine on Google Compute Engine. + + Args: + request (:class:`~.oslogin.GetLoginProfileRequest`): + The request object. A request message for retrieving the + login profile information for a user. + name (:class:`str`): + Required. The unique ID for the user in format + ``users/{user}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.oslogin.LoginProfile: + The user profile information used for + logging in to a virtual machine on + Google Compute Engine. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a oslogin.GetLoginProfileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, oslogin.GetLoginProfileRequest): + request = oslogin.GetLoginProfileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_login_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_ssh_public_key( + self, + request: oslogin.GetSshPublicKeyRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.SshPublicKey: + r"""Retrieves an SSH public key. + + Args: + request (:class:`~.oslogin.GetSshPublicKeyRequest`): + The request object. A request message for retrieving an + SSH public key. + name (:class:`str`): + Required. The fingerprint of the public key to retrieve. + Public keys are identified by their SHA-256 fingerprint. + The fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.SshPublicKey: + The SSH public key information + associated with a Google account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a oslogin.GetSshPublicKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, oslogin.GetSshPublicKeyRequest): + request = oslogin.GetSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ssh_public_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def import_ssh_public_key( + self, + request: oslogin.ImportSshPublicKeyRequest = None, + *, + parent: str = None, + ssh_public_key: common.SshPublicKey = None, + project_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> oslogin.ImportSshPublicKeyResponse: + r"""Adds an SSH public key and returns the profile + information. Default POSIX account information is set + when no username and UID exist as part of the login + profile. + + Args: + request (:class:`~.oslogin.ImportSshPublicKeyRequest`): + The request object. A request message for importing an + SSH public key. + parent (:class:`str`): + Required. The unique ID for the user in format + ``users/{user}``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ssh_public_key (:class:`~.common.SshPublicKey`): + Optional. The SSH public key and + expiration time. + This corresponds to the ``ssh_public_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + project_id (:class:`str`): + The project ID of the Google Cloud + Platform project. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.oslogin.ImportSshPublicKeyResponse: + A response message for importing an + SSH public key. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, ssh_public_key, project_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a oslogin.ImportSshPublicKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, oslogin.ImportSshPublicKeyRequest): + request = oslogin.ImportSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if ssh_public_key is not None: + request.ssh_public_key = ssh_public_key + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_ssh_public_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_ssh_public_key( + self, + request: oslogin.UpdateSshPublicKeyRequest = None, + *, + name: str = None, + ssh_public_key: common.SshPublicKey = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.SshPublicKey: + r"""Updates an SSH public key and returns the profile + information. This method supports patch semantics. + + Args: + request (:class:`~.oslogin.UpdateSshPublicKeyRequest`): + The request object. A request message for updating an + SSH public key. + name (:class:`str`): + Required. The fingerprint of the public key to update. + Public keys are identified by their SHA-256 fingerprint. + The fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ssh_public_key (:class:`~.common.SshPublicKey`): + Required. The SSH public key and + expiration time. + This corresponds to the ``ssh_public_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Mask to control which fields get + updated. Updates all if not present. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.SshPublicKey: + The SSH public key information + associated with a Google account. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, ssh_public_key, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a oslogin.UpdateSshPublicKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, oslogin.UpdateSshPublicKeyRequest): + request = oslogin.UpdateSshPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if ssh_public_key is not None: + request.ssh_public_key = ssh_public_key + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_ssh_public_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-os-login",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("OsLoginServiceClient",) diff --git a/google/cloud/oslogin_v1/services/os_login_service/transports/__init__.py b/google/cloud/oslogin_v1/services/os_login_service/transports/__init__.py new file mode 100644 index 0000000..67d67c9 --- /dev/null +++ b/google/cloud/oslogin_v1/services/os_login_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 OsLoginServiceTransport +from .grpc import OsLoginServiceGrpcTransport +from .grpc_asyncio import OsLoginServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OsLoginServiceTransport]] +_transport_registry["grpc"] = OsLoginServiceGrpcTransport +_transport_registry["grpc_asyncio"] = OsLoginServiceGrpcAsyncIOTransport + + +__all__ = ( + "OsLoginServiceTransport", + "OsLoginServiceGrpcTransport", + "OsLoginServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/oslogin_v1/services/os_login_service/transports/base.py b/google/cloud/oslogin_v1/services/os_login_service/transports/base.py new file mode 100644 index 0000000..5832582 --- /dev/null +++ b/google/cloud/oslogin_v1/services/os_login_service/transports/base.py @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.oslogin_v1 import common # type: ignore +from google.cloud.oslogin_v1.types import oslogin +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-os-login",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class OsLoginServiceTransport(abc.ABC): + """Abstract transport class for OsLoginService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + ) + + def __init__( + self, + *, + host: str = "oslogin.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.delete_posix_account: gapic_v1.method.wrap_method( + self.delete_posix_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=client_info, + ), + self.delete_ssh_public_key: gapic_v1.method.wrap_method( + self.delete_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=client_info, + ), + self.get_login_profile: gapic_v1.method.wrap_method( + self.get_login_profile, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=client_info, + ), + self.get_ssh_public_key: gapic_v1.method.wrap_method( + self.get_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=client_info, + ), + self.import_ssh_public_key: gapic_v1.method.wrap_method( + self.import_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=client_info, + ), + self.update_ssh_public_key: gapic_v1.method.wrap_method( + self.update_ssh_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=10.0, + client_info=client_info, + ), + } + + @property + def delete_posix_account( + self, + ) -> typing.Callable[ + [oslogin.DeletePosixAccountRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_ssh_public_key( + self, + ) -> typing.Callable[ + [oslogin.DeleteSshPublicKeyRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def get_login_profile( + self, + ) -> typing.Callable[ + [oslogin.GetLoginProfileRequest], + typing.Union[oslogin.LoginProfile, typing.Awaitable[oslogin.LoginProfile]], + ]: + raise NotImplementedError() + + @property + def get_ssh_public_key( + self, + ) -> typing.Callable[ + [oslogin.GetSshPublicKeyRequest], + typing.Union[common.SshPublicKey, typing.Awaitable[common.SshPublicKey]], + ]: + raise NotImplementedError() + + @property + def import_ssh_public_key( + self, + ) -> typing.Callable[ + [oslogin.ImportSshPublicKeyRequest], + typing.Union[ + oslogin.ImportSshPublicKeyResponse, + typing.Awaitable[oslogin.ImportSshPublicKeyResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_ssh_public_key( + self, + ) -> typing.Callable[ + [oslogin.UpdateSshPublicKeyRequest], + typing.Union[common.SshPublicKey, typing.Awaitable[common.SshPublicKey]], + ]: + raise NotImplementedError() + + +__all__ = ("OsLoginServiceTransport",) diff --git a/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py b/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py new file mode 100644 index 0000000..587a6c4 --- /dev/null +++ b/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py @@ -0,0 +1,401 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.oslogin_v1 import common # type: ignore +from google.cloud.oslogin_v1.types import oslogin +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO + + +class OsLoginServiceGrpcTransport(OsLoginServiceTransport): + """gRPC backend transport for OsLoginService. + + Cloud OS Login API + The Cloud OS Login API allows you to manage users and their + associated SSH public keys for logging into virtual machines on + Google Cloud Platform. + + 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 = "oslogin.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "oslogin.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def delete_posix_account( + self, + ) -> Callable[[oslogin.DeletePosixAccountRequest], empty.Empty]: + r"""Return a callable for the delete posix account method over gRPC. + + Deletes a POSIX account. + + Returns: + Callable[[~.DeletePosixAccountRequest], + ~.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_posix_account" not in self._stubs: + self._stubs["delete_posix_account"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount", + request_serializer=oslogin.DeletePosixAccountRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_posix_account"] + + @property + def delete_ssh_public_key( + self, + ) -> Callable[[oslogin.DeleteSshPublicKeyRequest], empty.Empty]: + r"""Return a callable for the delete ssh public key method over gRPC. + + Deletes an SSH public key. + + Returns: + Callable[[~.DeleteSshPublicKeyRequest], + ~.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_ssh_public_key" not in self._stubs: + self._stubs["delete_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/DeleteSshPublicKey", + request_serializer=oslogin.DeleteSshPublicKeyRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_ssh_public_key"] + + @property + def get_login_profile( + self, + ) -> Callable[[oslogin.GetLoginProfileRequest], oslogin.LoginProfile]: + r"""Return a callable for the get login profile method over gRPC. + + Retrieves the profile information used for logging in + to a virtual machine on Google Compute Engine. + + Returns: + Callable[[~.GetLoginProfileRequest], + ~.LoginProfile]: + 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_login_profile" not in self._stubs: + self._stubs["get_login_profile"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/GetLoginProfile", + request_serializer=oslogin.GetLoginProfileRequest.serialize, + response_deserializer=oslogin.LoginProfile.deserialize, + ) + return self._stubs["get_login_profile"] + + @property + def get_ssh_public_key( + self, + ) -> Callable[[oslogin.GetSshPublicKeyRequest], common.SshPublicKey]: + r"""Return a callable for the get ssh public key method over gRPC. + + Retrieves an SSH public key. + + Returns: + Callable[[~.GetSshPublicKeyRequest], + ~.SshPublicKey]: + 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_ssh_public_key" not in self._stubs: + self._stubs["get_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/GetSshPublicKey", + request_serializer=oslogin.GetSshPublicKeyRequest.serialize, + response_deserializer=common.SshPublicKey.deserialize, + ) + return self._stubs["get_ssh_public_key"] + + @property + def import_ssh_public_key( + self, + ) -> Callable[ + [oslogin.ImportSshPublicKeyRequest], oslogin.ImportSshPublicKeyResponse + ]: + r"""Return a callable for the import ssh public key method over gRPC. + + Adds an SSH public key and returns the profile + information. Default POSIX account information is set + when no username and UID exist as part of the login + profile. + + Returns: + Callable[[~.ImportSshPublicKeyRequest], + ~.ImportSshPublicKeyResponse]: + 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 "import_ssh_public_key" not in self._stubs: + self._stubs["import_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/ImportSshPublicKey", + request_serializer=oslogin.ImportSshPublicKeyRequest.serialize, + response_deserializer=oslogin.ImportSshPublicKeyResponse.deserialize, + ) + return self._stubs["import_ssh_public_key"] + + @property + def update_ssh_public_key( + self, + ) -> Callable[[oslogin.UpdateSshPublicKeyRequest], common.SshPublicKey]: + r"""Return a callable for the update ssh public key method over gRPC. + + Updates an SSH public key and returns the profile + information. This method supports patch semantics. + + Returns: + Callable[[~.UpdateSshPublicKeyRequest], + ~.SshPublicKey]: + 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_ssh_public_key" not in self._stubs: + self._stubs["update_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/UpdateSshPublicKey", + request_serializer=oslogin.UpdateSshPublicKeyRequest.serialize, + response_deserializer=common.SshPublicKey.deserialize, + ) + return self._stubs["update_ssh_public_key"] + + +__all__ = ("OsLoginServiceGrpcTransport",) diff --git a/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py b/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..63206d9 --- /dev/null +++ b/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.oslogin_v1 import common # type: ignore +from google.cloud.oslogin_v1.types import oslogin +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OsLoginServiceGrpcTransport + + +class OsLoginServiceGrpcAsyncIOTransport(OsLoginServiceTransport): + """gRPC AsyncIO backend transport for OsLoginService. + + Cloud OS Login API + The Cloud OS Login API allows you to manage users and their + associated SSH public keys for logging into virtual machines on + Google Cloud Platform. + + 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 = "oslogin.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "oslogin.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def delete_posix_account( + self, + ) -> Callable[[oslogin.DeletePosixAccountRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete posix account method over gRPC. + + Deletes a POSIX account. + + Returns: + Callable[[~.DeletePosixAccountRequest], + 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_posix_account" not in self._stubs: + self._stubs["delete_posix_account"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount", + request_serializer=oslogin.DeletePosixAccountRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_posix_account"] + + @property + def delete_ssh_public_key( + self, + ) -> Callable[[oslogin.DeleteSshPublicKeyRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete ssh public key method over gRPC. + + Deletes an SSH public key. + + Returns: + Callable[[~.DeleteSshPublicKeyRequest], + 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_ssh_public_key" not in self._stubs: + self._stubs["delete_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/DeleteSshPublicKey", + request_serializer=oslogin.DeleteSshPublicKeyRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_ssh_public_key"] + + @property + def get_login_profile( + self, + ) -> Callable[[oslogin.GetLoginProfileRequest], Awaitable[oslogin.LoginProfile]]: + r"""Return a callable for the get login profile method over gRPC. + + Retrieves the profile information used for logging in + to a virtual machine on Google Compute Engine. + + Returns: + Callable[[~.GetLoginProfileRequest], + Awaitable[~.LoginProfile]]: + 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_login_profile" not in self._stubs: + self._stubs["get_login_profile"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/GetLoginProfile", + request_serializer=oslogin.GetLoginProfileRequest.serialize, + response_deserializer=oslogin.LoginProfile.deserialize, + ) + return self._stubs["get_login_profile"] + + @property + def get_ssh_public_key( + self, + ) -> Callable[[oslogin.GetSshPublicKeyRequest], Awaitable[common.SshPublicKey]]: + r"""Return a callable for the get ssh public key method over gRPC. + + Retrieves an SSH public key. + + Returns: + Callable[[~.GetSshPublicKeyRequest], + Awaitable[~.SshPublicKey]]: + 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_ssh_public_key" not in self._stubs: + self._stubs["get_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/GetSshPublicKey", + request_serializer=oslogin.GetSshPublicKeyRequest.serialize, + response_deserializer=common.SshPublicKey.deserialize, + ) + return self._stubs["get_ssh_public_key"] + + @property + def import_ssh_public_key( + self, + ) -> Callable[ + [oslogin.ImportSshPublicKeyRequest], + Awaitable[oslogin.ImportSshPublicKeyResponse], + ]: + r"""Return a callable for the import ssh public key method over gRPC. + + Adds an SSH public key and returns the profile + information. Default POSIX account information is set + when no username and UID exist as part of the login + profile. + + Returns: + Callable[[~.ImportSshPublicKeyRequest], + Awaitable[~.ImportSshPublicKeyResponse]]: + 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 "import_ssh_public_key" not in self._stubs: + self._stubs["import_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/ImportSshPublicKey", + request_serializer=oslogin.ImportSshPublicKeyRequest.serialize, + response_deserializer=oslogin.ImportSshPublicKeyResponse.deserialize, + ) + return self._stubs["import_ssh_public_key"] + + @property + def update_ssh_public_key( + self, + ) -> Callable[[oslogin.UpdateSshPublicKeyRequest], Awaitable[common.SshPublicKey]]: + r"""Return a callable for the update ssh public key method over gRPC. + + Updates an SSH public key and returns the profile + information. This method supports patch semantics. + + Returns: + Callable[[~.UpdateSshPublicKeyRequest], + Awaitable[~.SshPublicKey]]: + 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_ssh_public_key" not in self._stubs: + self._stubs["update_ssh_public_key"] = self.grpc_channel.unary_unary( + "/google.cloud.oslogin.v1.OsLoginService/UpdateSshPublicKey", + request_serializer=oslogin.UpdateSshPublicKeyRequest.serialize, + response_deserializer=common.SshPublicKey.deserialize, + ) + return self._stubs["update_ssh_public_key"] + + +__all__ = ("OsLoginServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/oslogin_v1/types.py b/google/cloud/oslogin_v1/types.py deleted file mode 100644 index 8984776..0000000 --- a/google/cloud/oslogin_v1/types.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.oslogin_v1.proto import common_pb2 -from google.cloud.oslogin_v1.proto import oslogin_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_shared_modules = [ - common_pb2, - empty_pb2, - field_mask_pb2, -] - -_local_modules = [ - oslogin_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.oslogin_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/oslogin_v1/types/__init__.py b/google/cloud/oslogin_v1/types/__init__.py new file mode 100644 index 0000000..c36dc46 --- /dev/null +++ b/google/cloud/oslogin_v1/types/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .oslogin import ( + LoginProfile, + DeletePosixAccountRequest, + DeleteSshPublicKeyRequest, + GetLoginProfileRequest, + GetSshPublicKeyRequest, + ImportSshPublicKeyRequest, + ImportSshPublicKeyResponse, + UpdateSshPublicKeyRequest, +) + + +__all__ = ( + "LoginProfile", + "DeletePosixAccountRequest", + "DeleteSshPublicKeyRequest", + "GetLoginProfileRequest", + "GetSshPublicKeyRequest", + "ImportSshPublicKeyRequest", + "ImportSshPublicKeyResponse", + "UpdateSshPublicKeyRequest", +) diff --git a/google/cloud/oslogin_v1/types/oslogin.py b/google/cloud/oslogin_v1/types/oslogin.py new file mode 100644 index 0000000..f0e5fa3 --- /dev/null +++ b/google/cloud/oslogin_v1/types/oslogin.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.oslogin_v1 import common # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.oslogin.v1", + manifest={ + "LoginProfile", + "DeletePosixAccountRequest", + "DeleteSshPublicKeyRequest", + "GetLoginProfileRequest", + "GetSshPublicKeyRequest", + "ImportSshPublicKeyRequest", + "ImportSshPublicKeyResponse", + "UpdateSshPublicKeyRequest", + }, +) + + +class LoginProfile(proto.Message): + r"""The user profile information used for logging in to a virtual + machine on Google Compute Engine. + + Attributes: + name (str): + Required. A unique user ID. + posix_accounts (Sequence[~.common.PosixAccount]): + The list of POSIX accounts associated with + the user. + ssh_public_keys (Sequence[~.oslogin.LoginProfile.SshPublicKeysEntry]): + A map from SSH public key fingerprint to the + associated key object. + """ + + name = proto.Field(proto.STRING, number=1) + + posix_accounts = proto.RepeatedField( + proto.MESSAGE, number=2, message=common.PosixAccount, + ) + + ssh_public_keys = proto.MapField( + proto.STRING, proto.MESSAGE, number=3, message=common.SshPublicKey, + ) + + +class DeletePosixAccountRequest(proto.Message): + r"""A request message for deleting a POSIX account entry. + + Attributes: + name (str): + Required. A reference to the POSIX account to update. POSIX + accounts are identified by the project ID they are + associated with. A reference to the POSIX account is in + format ``users/{user}/projects/{project}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteSshPublicKeyRequest(proto.Message): + r"""A request message for deleting an SSH public key. + + Attributes: + name (str): + Required. The fingerprint of the public key to update. + Public keys are identified by their SHA-256 fingerprint. The + fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetLoginProfileRequest(proto.Message): + r"""A request message for retrieving the login profile + information for a user. + + Attributes: + name (str): + Required. The unique ID for the user in format + ``users/{user}``. + project_id (str): + The project ID of the Google Cloud Platform + project. + system_id (str): + A system ID for filtering the results of the + request. + """ + + name = proto.Field(proto.STRING, number=1) + + project_id = proto.Field(proto.STRING, number=2) + + system_id = proto.Field(proto.STRING, number=3) + + +class GetSshPublicKeyRequest(proto.Message): + r"""A request message for retrieving an SSH public key. + + Attributes: + name (str): + Required. The fingerprint of the public key to retrieve. + Public keys are identified by their SHA-256 fingerprint. The + fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ImportSshPublicKeyRequest(proto.Message): + r"""A request message for importing an SSH public key. + + Attributes: + parent (str): + Required. The unique ID for the user in format + ``users/{user}``. + ssh_public_key (~.common.SshPublicKey): + Optional. The SSH public key and expiration + time. + project_id (str): + The project ID of the Google Cloud Platform + project. + """ + + parent = proto.Field(proto.STRING, number=1) + + ssh_public_key = proto.Field(proto.MESSAGE, number=2, message=common.SshPublicKey,) + + project_id = proto.Field(proto.STRING, number=3) + + +class ImportSshPublicKeyResponse(proto.Message): + r"""A response message for importing an SSH public key. + + Attributes: + login_profile (~.oslogin.LoginProfile): + The login profile information for the user. + """ + + login_profile = proto.Field(proto.MESSAGE, number=1, message=LoginProfile,) + + +class UpdateSshPublicKeyRequest(proto.Message): + r"""A request message for updating an SSH public key. + + Attributes: + name (str): + Required. The fingerprint of the public key to update. + Public keys are identified by their SHA-256 fingerprint. The + fingerprint of the public key is in format + ``users/{user}/sshPublicKeys/{fingerprint}``. + ssh_public_key (~.common.SshPublicKey): + Required. The SSH public key and expiration + time. + update_mask (~.field_mask.FieldMask): + Mask to control which fields get updated. + Updates all if not present. + """ + + name = proto.Field(proto.STRING, number=1) + + ssh_public_key = proto.Field(proto.MESSAGE, number=2, message=common.SshPublicKey,) + + update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index 2981137..9600c90 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -100,6 +102,10 @@ def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -135,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=70") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") @@ -145,7 +151,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -160,3 +166,38 @@ def docs(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + # sphinx-docfx-yaml supports up to sphinx version 1.5.5. + # https://github.com/docascode/sphinx-docfx-yaml/issues/97 + session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md new file mode 100644 index 0000000..55c97b3 --- /dev/null +++ b/samples/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md new file mode 100644 index 0000000..34c882b --- /dev/null +++ b/samples/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh index ff599eb..21f6d2a 100755 --- a/scripts/decrypt-secrets.sh +++ b/scripts/decrypt-secrets.sh @@ -20,14 +20,27 @@ ROOT=$( dirname "$DIR" ) # Work from the project root. cd $ROOT +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + # Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ > testing/test-env.sh gcloud secrets versions access latest \ --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ > testing/service-account.json gcloud secrets versions access latest \ --secret="python-docs-samples-client-secrets" \ - > testing/client-secrets.json \ No newline at end of file + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/scripts/fixup_oslogin_v1_keywords.py b/scripts/fixup_oslogin_v1_keywords.py new file mode 100644 index 0000000..01ff867 --- /dev/null +++ b/scripts/fixup_oslogin_v1_keywords.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class osloginCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'delete_posix_account': ('name', ), + 'delete_ssh_public_key': ('name', ), + 'get_login_profile': ('name', 'project_id', 'system_id', ), + 'get_ssh_public_key': ('name', ), + 'import_ssh_public_key': ('parent', 'ssh_public_key', 'project_id', ), + 'update_ssh_public_key': ('name', 'ssh_public_key', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=osloginCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the oslogin client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index f3aafb8..c1533df 100644 --- a/setup.py +++ b/setup.py @@ -28,7 +28,11 @@ # 'Development Status :: 4 - Beta' # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" -dependencies = ["google-api-core[grpc] >= 1.14.0, < 2.0.0dev"] +dependencies = [ + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "proto-plus >= 1.4.0", + "libcst >= 0.2.5", +] extras = {} @@ -43,7 +47,9 @@ # Only include packages under the 'google' namespace. Do not include tests, # benchmarks, etc. packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] # Determine which namespaces are needed. @@ -66,12 +72,10 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -80,7 +84,8 @@ namespace_packages=namespaces, install_requires=dependencies, extras_require=extras, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=["scripts/fixup_oslogin_v1_keywords.py"], include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index eb99d89..6538a74 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,22 +4,14 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-oslogin.git", - "sha": "f0254af9a85859f55bf1dbc7608c4a19be270368" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "cf41866c6f14f10a07aa1e2a1260fc0a2727d889", - "internalRef": "317812187" + "sha": "98e8b892553dafba3fd1ec10146c8366cd2da4bf" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "cf2eff09d0f5319a4dc5cdce2b6356d85af4a798" + "sha": "0762e8ee2ec21cdfc4d82020b985a104feb0453b" } } ], diff --git a/synth.py b/synth.py index b561042..e6e9417 100644 --- a/synth.py +++ b/synth.py @@ -18,6 +18,7 @@ gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() +excludes = ["README.rst", "setup.py", "nox*.py", "docs/index.rst"] # ---------------------------------------------------------------------------- # Generate oslogin GAPIC layer @@ -28,42 +29,54 @@ bazel_target="//google/cloud/oslogin/v1:oslogin-v1-py", include_protos=True, ) -# pb2's are incorrectly generated into deeper directories, so copy separately into proto/ -s.move( - library, - excludes=[ - "nox.py", - "setup.py", - "README.rst", - "docs/index.rst", - library / "google/cloud/oslogin_v1/proto/oslogin/**", - library / "google/cloud/oslogin_v1/proto/oslogin_v1/**", - ], + +s.move(library / "google/cloud/oslogin_v1") + +s.move(library / "google/cloud/oslogin", excludes=[library / "google/cloud/oslogin/common/**/*"]) +s.move(library / "google/cloud/oslogin/common", "google/cloud/oslogin_v1/common", excludes=[library / "google/cloud/oslogin/common/services"]) + +s.move(library / "tests/unit/gapic/oslogin_v1") + +s.move(library / "scripts/fixup_oslogin_v1_keywords.py") + +s.move(library / "docs", excludes=[library / "docs/index.rst", library / "docs/common"]) +s.move(library / "docs/common", "docs/oslogin_v1/common", excludes=[library / "docs/common/services.rst"]) +s.replace( + "docs/oslogin_v1/common/types.rst", + "google.cloud.oslogin.common.types", + "google.cloud.oslogin_v1.common" ) -s.move(library / "google/cloud/oslogin_v1/proto/**/*.py", "google/cloud/oslogin_v1/proto") -s.move(library / "google/cloud/oslogin/common/**/*.py", "google/cloud/oslogin_v1/proto") s.replace( - "google/cloud/oslogin_v1/gapic/os_login_service_client.py", + "google/cloud/oslogin_v1/**/*.py", "google-cloud-oslogin", "google-cloud-os-login", ) -# Fix up imports +for file in ["google/cloud/**/*.py", "tests/**/*.py"]: + s.replace( + file, + "from google.cloud.oslogin.common import common_pb2 as common", + "from google.cloud.oslogin_v1 import common" + ) s.replace( - "google/**/proto/*.py", - "from google.cloud.oslogin.common import common_pb2", - "from google.cloud.oslogin_v1.proto import common_pb2", + "google/cloud/oslogin_v1/**/*.py", + "google.cloud.oslogin.common", + "google.cloud.oslogin.v1" +) +s.replace( + "google/cloud/oslogin_v1/**/*.py", + "SshPublicKey.FromString", + "SshPublicKey.deserialize" ) # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=70) -s.move(templated_files) - -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"') - +templated_files = common.py_library( + samples=False, # set to True only if there are samples + microgenerator=True, +) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/unit/gapic/oslogin_v1/__init__.py b/tests/unit/gapic/oslogin_v1/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/unit/gapic/oslogin_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/oslogin_v1/test_os_login_service.py b/tests/unit/gapic/oslogin_v1/test_os_login_service.py new file mode 100644 index 0000000..bb077d5 --- /dev/null +++ b/tests/unit/gapic/oslogin_v1/test_os_login_service.py @@ -0,0 +1,2016 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.oslogin_v1 import common # type: ignore +from google.cloud.oslogin_v1.services.os_login_service import OsLoginServiceAsyncClient +from google.cloud.oslogin_v1.services.os_login_service import OsLoginServiceClient +from google.cloud.oslogin_v1.services.os_login_service import transports +from google.cloud.oslogin_v1.types import oslogin +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert OsLoginServiceClient._get_default_mtls_endpoint(None) is None + assert ( + OsLoginServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OsLoginServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OsLoginServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OsLoginServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OsLoginServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [OsLoginServiceClient, OsLoginServiceAsyncClient] +) +def test_os_login_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "oslogin.googleapis.com:443" + + +def test_os_login_service_client_get_transport_class(): + transport = OsLoginServiceClient.get_transport_class() + assert transport == transports.OsLoginServiceGrpcTransport + + transport = OsLoginServiceClient.get_transport_class("grpc") + assert transport == transports.OsLoginServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc"), + ( + OsLoginServiceAsyncClient, + transports.OsLoginServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + OsLoginServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsLoginServiceClient), +) +@mock.patch.object( + OsLoginServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsLoginServiceAsyncClient), +) +def test_os_login_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(OsLoginServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(OsLoginServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc", "true"), + ( + OsLoginServiceAsyncClient, + transports.OsLoginServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc", "false"), + ( + OsLoginServiceAsyncClient, + transports.OsLoginServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + OsLoginServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsLoginServiceClient), +) +@mock.patch.object( + OsLoginServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsLoginServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_os_login_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc"), + ( + OsLoginServiceAsyncClient, + transports.OsLoginServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_os_login_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc"), + ( + OsLoginServiceAsyncClient, + transports.OsLoginServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_os_login_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_os_login_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = OsLoginServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_delete_posix_account( + transport: str = "grpc", request_type=oslogin.DeletePosixAccountRequest +): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_posix_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_posix_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == oslogin.DeletePosixAccountRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_posix_account_from_dict(): + test_delete_posix_account(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_posix_account_async(transport: str = "grpc_asyncio"): + client = OsLoginServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = oslogin.DeletePosixAccountRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_posix_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_posix_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_posix_account_field_headers(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.DeletePosixAccountRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_posix_account), "__call__" + ) as call: + call.return_value = None + + client.delete_posix_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_posix_account_field_headers_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.DeletePosixAccountRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_posix_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_posix_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_posix_account_flattened(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_posix_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_posix_account(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_posix_account_flattened_error(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_posix_account( + oslogin.DeletePosixAccountRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_posix_account_flattened_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_posix_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_posix_account(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_posix_account_flattened_error_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_posix_account( + oslogin.DeletePosixAccountRequest(), name="name_value", + ) + + +def test_delete_ssh_public_key( + transport: str = "grpc", request_type=oslogin.DeleteSshPublicKeyRequest +): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == oslogin.DeleteSshPublicKeyRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_ssh_public_key_from_dict(): + test_delete_ssh_public_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_ssh_public_key_async(transport: str = "grpc_asyncio"): + client = OsLoginServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = oslogin.DeleteSshPublicKeyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_ssh_public_key_field_headers(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.DeleteSshPublicKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_ssh_public_key), "__call__" + ) as call: + call.return_value = None + + client.delete_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_ssh_public_key_field_headers_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.DeleteSshPublicKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_ssh_public_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_ssh_public_key_flattened(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_ssh_public_key(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_ssh_public_key_flattened_error(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_ssh_public_key( + oslogin.DeleteSshPublicKeyRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_ssh_public_key_flattened_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_ssh_public_key(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_ssh_public_key_flattened_error_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_ssh_public_key( + oslogin.DeleteSshPublicKeyRequest(), name="name_value", + ) + + +def test_get_login_profile( + transport: str = "grpc", request_type=oslogin.GetLoginProfileRequest +): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_login_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = oslogin.LoginProfile(name="name_value",) + + response = client.get_login_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == oslogin.GetLoginProfileRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, oslogin.LoginProfile) + + assert response.name == "name_value" + + +def test_get_login_profile_from_dict(): + test_get_login_profile(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_login_profile_async(transport: str = "grpc_asyncio"): + client = OsLoginServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = oslogin.GetLoginProfileRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_login_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.LoginProfile(name="name_value",) + ) + + response = await client.get_login_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, oslogin.LoginProfile) + + assert response.name == "name_value" + + +def test_get_login_profile_field_headers(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.GetLoginProfileRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_login_profile), "__call__" + ) as call: + call.return_value = oslogin.LoginProfile() + + client.get_login_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_login_profile_field_headers_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.GetLoginProfileRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_login_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.LoginProfile() + ) + + await client.get_login_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_login_profile_flattened(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_login_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = oslogin.LoginProfile() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_login_profile(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_login_profile_flattened_error(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_login_profile( + oslogin.GetLoginProfileRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_login_profile_flattened_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_login_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = oslogin.LoginProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.LoginProfile() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_login_profile(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_login_profile_flattened_error_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_login_profile( + oslogin.GetLoginProfileRequest(), name="name_value", + ) + + +def test_get_ssh_public_key( + transport: str = "grpc", request_type=oslogin.GetSshPublicKeyRequest +): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + + response = client.get_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == oslogin.GetSshPublicKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + + assert response.key == "key_value" + + assert response.expiration_time_usec == 2144 + + assert response.fingerprint == "fingerprint_value" + + assert response.name == "name_value" + + +def test_get_ssh_public_key_from_dict(): + test_get_ssh_public_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_ssh_public_key_async(transport: str = "grpc_asyncio"): + client = OsLoginServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = oslogin.GetSshPublicKeyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + ) + + response = await client.get_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + + assert response.key == "key_value" + + assert response.expiration_time_usec == 2144 + + assert response.fingerprint == "fingerprint_value" + + assert response.name == "name_value" + + +def test_get_ssh_public_key_field_headers(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.GetSshPublicKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_ssh_public_key), "__call__" + ) as call: + call.return_value = common.SshPublicKey() + + client.get_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_ssh_public_key_field_headers_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.GetSshPublicKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_ssh_public_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey()) + + await client.get_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_ssh_public_key_flattened(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = common.SshPublicKey() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ssh_public_key(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_ssh_public_key_flattened_error(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_ssh_public_key( + oslogin.GetSshPublicKeyRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_ssh_public_key_flattened_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = common.SshPublicKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ssh_public_key(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_ssh_public_key_flattened_error_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ssh_public_key( + oslogin.GetSshPublicKeyRequest(), name="name_value", + ) + + +def test_import_ssh_public_key( + transport: str = "grpc", request_type=oslogin.ImportSshPublicKeyRequest +): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = oslogin.ImportSshPublicKeyResponse() + + response = client.import_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == oslogin.ImportSshPublicKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, oslogin.ImportSshPublicKeyResponse) + + +def test_import_ssh_public_key_from_dict(): + test_import_ssh_public_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_import_ssh_public_key_async(transport: str = "grpc_asyncio"): + client = OsLoginServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = oslogin.ImportSshPublicKeyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.ImportSshPublicKeyResponse() + ) + + response = await client.import_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, oslogin.ImportSshPublicKeyResponse) + + +def test_import_ssh_public_key_field_headers(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.ImportSshPublicKeyRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_ssh_public_key), "__call__" + ) as call: + call.return_value = oslogin.ImportSshPublicKeyResponse() + + client.import_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_ssh_public_key_field_headers_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.ImportSshPublicKeyRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_ssh_public_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.ImportSshPublicKeyResponse() + ) + + await client.import_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_import_ssh_public_key_flattened(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = oslogin.ImportSshPublicKeyResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_ssh_public_key( + parent="parent_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + project_id="project_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].ssh_public_key == common.SshPublicKey(key="key_value") + + assert args[0].project_id == "project_id_value" + + +def test_import_ssh_public_key_flattened_error(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_ssh_public_key( + oslogin.ImportSshPublicKeyRequest(), + parent="parent_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + project_id="project_id_value", + ) + + +@pytest.mark.asyncio +async def test_import_ssh_public_key_flattened_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = oslogin.ImportSshPublicKeyResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.ImportSshPublicKeyResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_ssh_public_key( + parent="parent_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + project_id="project_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].ssh_public_key == common.SshPublicKey(key="key_value") + + assert args[0].project_id == "project_id_value" + + +@pytest.mark.asyncio +async def test_import_ssh_public_key_flattened_error_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_ssh_public_key( + oslogin.ImportSshPublicKeyRequest(), + parent="parent_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + project_id="project_id_value", + ) + + +def test_update_ssh_public_key( + transport: str = "grpc", request_type=oslogin.UpdateSshPublicKeyRequest +): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + + response = client.update_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == oslogin.UpdateSshPublicKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + + assert response.key == "key_value" + + assert response.expiration_time_usec == 2144 + + assert response.fingerprint == "fingerprint_value" + + assert response.name == "name_value" + + +def test_update_ssh_public_key_from_dict(): + test_update_ssh_public_key(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_ssh_public_key_async(transport: str = "grpc_asyncio"): + client = OsLoginServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = oslogin.UpdateSshPublicKeyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + ) + + response = await client.update_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + + assert response.key == "key_value" + + assert response.expiration_time_usec == 2144 + + assert response.fingerprint == "fingerprint_value" + + assert response.name == "name_value" + + +def test_update_ssh_public_key_field_headers(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.UpdateSshPublicKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_ssh_public_key), "__call__" + ) as call: + call.return_value = common.SshPublicKey() + + client.update_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_ssh_public_key_field_headers_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = oslogin.UpdateSshPublicKeyRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_ssh_public_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey()) + + await client.update_ssh_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_update_ssh_public_key_flattened(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = common.SshPublicKey() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_ssh_public_key( + name="name_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].ssh_public_key == common.SshPublicKey(key="key_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_ssh_public_key_flattened_error(): + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_ssh_public_key( + oslogin.UpdateSshPublicKeyRequest(), + name="name_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_ssh_public_key_flattened_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = common.SshPublicKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_ssh_public_key( + name="name_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].ssh_public_key == common.SshPublicKey(key="key_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_ssh_public_key_flattened_error_async(): + client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_ssh_public_key( + oslogin.UpdateSshPublicKeyRequest(), + name="name_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsLoginServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsLoginServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = OsLoginServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OsLoginServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsLoginServiceGrpcTransport, + transports.OsLoginServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.OsLoginServiceGrpcTransport,) + + +def test_os_login_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.OsLoginServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_os_login_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.OsLoginServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete_posix_account", + "delete_ssh_public_key", + "get_login_profile", + "get_ssh_public_key", + "import_ssh_public_key", + "update_ssh_public_key", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_os_login_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.OsLoginServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + ), + quota_project_id="octopus", + ) + + +def test_os_login_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.OsLoginServiceTransport() + adc.assert_called_once() + + +def test_os_login_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + OsLoginServiceClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + ), + quota_project_id=None, + ) + + +def test_os_login_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.OsLoginServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + ), + quota_project_id="octopus", + ) + + +def test_os_login_service_host_no_port(): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="oslogin.googleapis.com" + ), + ) + assert client._transport._host == "oslogin.googleapis.com:443" + + +def test_os_login_service_host_with_port(): + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="oslogin.googleapis.com:8000" + ), + ) + assert client._transport._host == "oslogin.googleapis.com:8000" + + +def test_os_login_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.OsLoginServiceGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_os_login_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.OsLoginServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsLoginServiceGrpcTransport, + transports.OsLoginServiceGrpcAsyncIOTransport, + ], +) +def test_os_login_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsLoginServiceGrpcTransport, + transports.OsLoginServiceGrpcAsyncIOTransport, + ], +) +def test_os_login_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/compute", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_ssh_public_key_path(): + user = "squid" + fingerprint = "clam" + + expected = "users/{user}/sshPublicKeys/{fingerprint}".format( + user=user, fingerprint=fingerprint, + ) + actual = OsLoginServiceClient.ssh_public_key_path(user, fingerprint) + assert expected == actual + + +def test_parse_ssh_public_key_path(): + expected = { + "user": "whelk", + "fingerprint": "octopus", + } + path = OsLoginServiceClient.ssh_public_key_path(**expected) + + # Check that the path construction is reversible. + actual = OsLoginServiceClient.parse_ssh_public_key_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.OsLoginServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = OsLoginServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.OsLoginServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = OsLoginServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/v1/test_os_login_service_client_v1.py b/tests/unit/gapic/v1/test_os_login_service_client_v1.py deleted file mode 100644 index 66fae90..0000000 --- a/tests/unit/gapic/v1/test_os_login_service_client_v1.py +++ /dev/null @@ -1,296 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import oslogin_v1 -from google.cloud.oslogin_v1.proto import common_pb2 -from google.cloud.oslogin_v1.proto import oslogin_pb2 -from google.protobuf import empty_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestOsLoginServiceClient(object): - def test_delete_posix_account(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup Request - name = client.posix_account_path("[USER]", "[PROJECT]") - - client.delete_posix_account(name) - - assert len(channel.requests) == 1 - expected_request = oslogin_pb2.DeletePosixAccountRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_posix_account_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup request - name = client.posix_account_path("[USER]", "[PROJECT]") - - with pytest.raises(CustomException): - client.delete_posix_account(name) - - def test_delete_ssh_public_key(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup Request - name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]") - - client.delete_ssh_public_key(name) - - assert len(channel.requests) == 1 - expected_request = oslogin_pb2.DeleteSshPublicKeyRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_ssh_public_key_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup request - name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]") - - with pytest.raises(CustomException): - client.delete_ssh_public_key(name) - - def test_get_login_profile(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = oslogin_pb2.LoginProfile(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup Request - name = client.user_path("[USER]") - - response = client.get_login_profile(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = oslogin_pb2.GetLoginProfileRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_login_profile_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup request - name = client.user_path("[USER]") - - with pytest.raises(CustomException): - client.get_login_profile(name) - - def test_get_ssh_public_key(self): - # Setup Expected Response - key = "key106079" - expiration_time_usec = 2058878882 - fingerprint = "fingerprint-1375934236" - name_2 = "name2-1052831874" - expected_response = { - "key": key, - "expiration_time_usec": expiration_time_usec, - "fingerprint": fingerprint, - "name": name_2, - } - expected_response = common_pb2.SshPublicKey(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup Request - name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]") - - response = client.get_ssh_public_key(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = oslogin_pb2.GetSshPublicKeyRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_ssh_public_key_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup request - name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]") - - with pytest.raises(CustomException): - client.get_ssh_public_key(name) - - def test_import_ssh_public_key(self): - # Setup Expected Response - expected_response = {} - expected_response = oslogin_pb2.ImportSshPublicKeyResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup Request - parent = client.user_path("[USER]") - - response = client.import_ssh_public_key(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = oslogin_pb2.ImportSshPublicKeyRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_import_ssh_public_key_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup request - parent = client.user_path("[USER]") - - with pytest.raises(CustomException): - client.import_ssh_public_key(parent) - - def test_update_ssh_public_key(self): - # Setup Expected Response - key = "key106079" - expiration_time_usec = 2058878882 - fingerprint = "fingerprint-1375934236" - name_2 = "name2-1052831874" - expected_response = { - "key": key, - "expiration_time_usec": expiration_time_usec, - "fingerprint": fingerprint, - "name": name_2, - } - expected_response = common_pb2.SshPublicKey(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup Request - name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]") - ssh_public_key = {} - - response = client.update_ssh_public_key(name, ssh_public_key) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = oslogin_pb2.UpdateSshPublicKeyRequest( - name=name, ssh_public_key=ssh_public_key - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_ssh_public_key_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = oslogin_v1.OsLoginServiceClient() - - # Setup request - name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]") - ssh_public_key = {} - - with pytest.raises(CustomException): - client.update_ssh_public_key(name, ssh_public_key)