1# -*- coding: utf-8 -*-
2# Copyright 2023 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16import abc
17from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
18
19import google.api_core
20from google.api_core import exceptions as core_exceptions
21from google.api_core import gapic_v1
22from google.api_core import retry as retries
23import google.auth # type: ignore
24from google.auth import credentials as ga_credentials # type: ignore
25from google.oauth2 import service_account # type: ignore
26
27from google.cloud.iam_credentials_v1 import gapic_version as package_version
28from google.cloud.iam_credentials_v1.types import common
29
30DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
31 gapic_version=package_version.__version__
32)
33
34
35class IAMCredentialsTransport(abc.ABC):
36 """Abstract transport class for IAMCredentials."""
37
38 AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
39
40 DEFAULT_HOST: str = "iamcredentials.googleapis.com"
41
42 def __init__(
43 self,
44 *,
45 host: str = DEFAULT_HOST,
46 credentials: Optional[ga_credentials.Credentials] = None,
47 credentials_file: Optional[str] = None,
48 scopes: Optional[Sequence[str]] = None,
49 quota_project_id: Optional[str] = None,
50 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
51 always_use_jwt_access: Optional[bool] = False,
52 api_audience: Optional[str] = None,
53 **kwargs,
54 ) -> None:
55 """Instantiate the transport.
56
57 Args:
58 host (Optional[str]):
59 The hostname to connect to.
60 credentials (Optional[google.auth.credentials.Credentials]): The
61 authorization credentials to attach to requests. These
62 credentials identify the application to the service; if none
63 are specified, the client will attempt to ascertain the
64 credentials from the environment.
65 credentials_file (Optional[str]): A file with credentials that can
66 be loaded with :func:`google.auth.load_credentials_from_file`.
67 This argument is mutually exclusive with credentials.
68 scopes (Optional[Sequence[str]]): A list of scopes.
69 quota_project_id (Optional[str]): An optional project to use for billing
70 and quota.
71 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
72 The client info used to send a user-agent string along with
73 API requests. If ``None``, then default info will be used.
74 Generally, you only need to set this if you're developing
75 your own client library.
76 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
77 be used for service account credentials.
78 """
79
80 scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
81
82 # Save the scopes.
83 self._scopes = scopes
84
85 # If no credentials are provided, then determine the appropriate
86 # defaults.
87 if credentials and credentials_file:
88 raise core_exceptions.DuplicateCredentialArgs(
89 "'credentials_file' and 'credentials' are mutually exclusive"
90 )
91
92 if credentials_file is not None:
93 credentials, _ = google.auth.load_credentials_from_file(
94 credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
95 )
96 elif credentials is None:
97 credentials, _ = google.auth.default(
98 **scopes_kwargs, quota_project_id=quota_project_id
99 )
100 # Don't apply audience if the credentials file passed from user.
101 if hasattr(credentials, "with_gdch_audience"):
102 credentials = credentials.with_gdch_audience(
103 api_audience if api_audience else host
104 )
105
106 # If the credentials are service account credentials, then always try to use self signed JWT.
107 if (
108 always_use_jwt_access
109 and isinstance(credentials, service_account.Credentials)
110 and hasattr(service_account.Credentials, "with_always_use_jwt_access")
111 ):
112 credentials = credentials.with_always_use_jwt_access(True)
113
114 # Save the credentials.
115 self._credentials = credentials
116
117 # Save the hostname. Default to port 443 (HTTPS) if none is specified.
118 if ":" not in host:
119 host += ":443"
120 self._host = host
121
122 def _prep_wrapped_messages(self, client_info):
123 # Precompute the wrapped methods.
124 self._wrapped_methods = {
125 self.generate_access_token: gapic_v1.method.wrap_method(
126 self.generate_access_token,
127 default_retry=retries.Retry(
128 initial=0.1,
129 maximum=60.0,
130 multiplier=1.3,
131 predicate=retries.if_exception_type(
132 core_exceptions.DeadlineExceeded,
133 core_exceptions.ServiceUnavailable,
134 ),
135 deadline=60.0,
136 ),
137 default_timeout=60.0,
138 client_info=client_info,
139 ),
140 self.generate_id_token: gapic_v1.method.wrap_method(
141 self.generate_id_token,
142 default_retry=retries.Retry(
143 initial=0.1,
144 maximum=60.0,
145 multiplier=1.3,
146 predicate=retries.if_exception_type(
147 core_exceptions.DeadlineExceeded,
148 core_exceptions.ServiceUnavailable,
149 ),
150 deadline=60.0,
151 ),
152 default_timeout=60.0,
153 client_info=client_info,
154 ),
155 self.sign_blob: gapic_v1.method.wrap_method(
156 self.sign_blob,
157 default_retry=retries.Retry(
158 initial=0.1,
159 maximum=60.0,
160 multiplier=1.3,
161 predicate=retries.if_exception_type(
162 core_exceptions.DeadlineExceeded,
163 core_exceptions.ServiceUnavailable,
164 ),
165 deadline=60.0,
166 ),
167 default_timeout=60.0,
168 client_info=client_info,
169 ),
170 self.sign_jwt: gapic_v1.method.wrap_method(
171 self.sign_jwt,
172 default_retry=retries.Retry(
173 initial=0.1,
174 maximum=60.0,
175 multiplier=1.3,
176 predicate=retries.if_exception_type(
177 core_exceptions.DeadlineExceeded,
178 core_exceptions.ServiceUnavailable,
179 ),
180 deadline=60.0,
181 ),
182 default_timeout=60.0,
183 client_info=client_info,
184 ),
185 }
186
187 def close(self):
188 """Closes resources associated with the transport.
189
190 .. warning::
191 Only call this method if the transport is NOT shared
192 with other clients - this may cause errors in other clients!
193 """
194 raise NotImplementedError()
195
196 @property
197 def generate_access_token(
198 self,
199 ) -> Callable[
200 [common.GenerateAccessTokenRequest],
201 Union[
202 common.GenerateAccessTokenResponse,
203 Awaitable[common.GenerateAccessTokenResponse],
204 ],
205 ]:
206 raise NotImplementedError()
207
208 @property
209 def generate_id_token(
210 self,
211 ) -> Callable[
212 [common.GenerateIdTokenRequest],
213 Union[
214 common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse]
215 ],
216 ]:
217 raise NotImplementedError()
218
219 @property
220 def sign_blob(
221 self,
222 ) -> Callable[
223 [common.SignBlobRequest],
224 Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]],
225 ]:
226 raise NotImplementedError()
227
228 @property
229 def sign_jwt(
230 self,
231 ) -> Callable[
232 [common.SignJwtRequest],
233 Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]],
234 ]:
235 raise NotImplementedError()
236
237 @property
238 def kind(self) -> str:
239 raise NotImplementedError()
240
241
242__all__ = ("IAMCredentialsTransport",)