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