Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py: 47%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

93 statements  

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 inspect 

17import json 

18import logging as std_logging 

19import pickle 

20import warnings 

21from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 

22 

23import google.protobuf.message 

24import grpc # type: ignore 

25import proto # type: ignore 

26from google.api_core import exceptions as core_exceptions 

27from google.api_core import gapic_v1, grpc_helpers_async 

28from google.api_core import retry_async as retries 

29from google.auth import credentials as ga_credentials # type: ignore 

30from google.auth.transport.grpc import SslCredentials # type: ignore 

31from google.protobuf.json_format import MessageToJson 

32from grpc.experimental import aio # type: ignore 

33 

34from google.cloud.iam_credentials_v1.types import common 

35 

36from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport 

37from .grpc import IAMCredentialsGrpcTransport 

38 

39try: 

40 from google.api_core import client_logging # type: ignore 

41 

42 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

43except ImportError: # pragma: NO COVER 

44 CLIENT_LOGGING_SUPPORTED = False 

45 

46_LOGGER = std_logging.getLogger(__name__) 

47 

48 

49class _LoggingClientAIOInterceptor( 

50 grpc.aio.UnaryUnaryClientInterceptor 

51): # pragma: NO COVER 

52 async def intercept_unary_unary(self, continuation, client_call_details, request): 

53 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

54 std_logging.DEBUG 

55 ) 

56 if logging_enabled: # pragma: NO COVER 

57 request_metadata = client_call_details.metadata 

58 if isinstance(request, proto.Message): 

59 request_payload = type(request).to_json(request) 

60 elif isinstance(request, google.protobuf.message.Message): 

61 request_payload = MessageToJson(request) 

62 else: 

63 request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" 

64 

65 request_metadata = { 

66 key: value.decode("utf-8") if isinstance(value, bytes) else value 

67 for key, value in request_metadata 

68 } 

69 grpc_request = { 

70 "payload": request_payload, 

71 "requestMethod": "grpc", 

72 "metadata": dict(request_metadata), 

73 } 

74 _LOGGER.debug( 

75 f"Sending request for {client_call_details.method}", 

76 extra={ 

77 "serviceName": "google.iam.credentials.v1.IAMCredentials", 

78 "rpcName": str(client_call_details.method), 

79 "request": grpc_request, 

80 "metadata": grpc_request["metadata"], 

81 }, 

82 ) 

83 response = await continuation(client_call_details, request) 

84 if logging_enabled: # pragma: NO COVER 

85 response_metadata = await response.trailing_metadata() 

86 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples 

87 metadata = ( 

88 dict([(k, str(v)) for k, v in response_metadata]) 

89 if response_metadata 

90 else None 

91 ) 

92 result = await response 

93 if isinstance(result, proto.Message): 

94 response_payload = type(result).to_json(result) 

95 elif isinstance(result, google.protobuf.message.Message): 

96 response_payload = MessageToJson(result) 

97 else: 

98 response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" 

99 grpc_response = { 

100 "payload": response_payload, 

101 "metadata": metadata, 

102 "status": "OK", 

103 } 

104 _LOGGER.debug( 

105 f"Received response to rpc {client_call_details.method}.", 

106 extra={ 

107 "serviceName": "google.iam.credentials.v1.IAMCredentials", 

108 "rpcName": str(client_call_details.method), 

109 "response": grpc_response, 

110 "metadata": grpc_response["metadata"], 

111 }, 

112 ) 

113 return response 

114 

115 

116class IAMCredentialsGrpcAsyncIOTransport(IAMCredentialsTransport): 

117 """gRPC AsyncIO backend transport for IAMCredentials. 

118 

119 A service account is a special type of Google account that 

120 belongs to your application or a virtual machine (VM), instead 

121 of to an individual end user. Your application assumes the 

122 identity of the service account to call Google APIs, so that the 

123 users aren't directly involved. 

124 

125 Service account credentials are used to temporarily assume the 

126 identity of the service account. Supported credential types 

127 include OAuth 2.0 access tokens, OpenID Connect ID tokens, 

128 self-signed JSON Web Tokens (JWTs), and more. 

129 

130 This class defines the same methods as the primary client, so the 

131 primary client can load the underlying transport implementation 

132 and call it. 

133 

134 It sends protocol buffers over the wire using gRPC (which is built on 

135 top of HTTP/2); the ``grpcio`` package must be installed. 

136 """ 

137 

138 _grpc_channel: aio.Channel 

139 _stubs: Dict[str, Callable] = {} 

140 

141 @classmethod 

142 def create_channel( 

143 cls, 

144 host: str = "iamcredentials.googleapis.com", 

145 credentials: Optional[ga_credentials.Credentials] = None, 

146 credentials_file: Optional[str] = None, 

147 scopes: Optional[Sequence[str]] = None, 

148 quota_project_id: Optional[str] = None, 

149 **kwargs, 

150 ) -> aio.Channel: 

151 """Create and return a gRPC AsyncIO channel object. 

152 Args: 

153 host (Optional[str]): The host for the channel to use. 

154 credentials (Optional[~.Credentials]): The 

155 authorization credentials to attach to requests. These 

156 credentials identify this application to the service. If 

157 none are specified, the client will attempt to ascertain 

158 the credentials from the environment. 

159 credentials_file (Optional[str]): Deprecated. A file with credentials that can 

160 be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be 

161 removed in the next major version of this library. 

162 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this 

163 service. These are only used when credentials are not specified and 

164 are passed to :func:`google.auth.default`. 

165 quota_project_id (Optional[str]): An optional project to use for billing 

166 and quota. 

167 kwargs (Optional[dict]): Keyword arguments, which are passed to the 

168 channel creation. 

169 Returns: 

170 aio.Channel: A gRPC AsyncIO channel object. 

171 """ 

172 

173 return grpc_helpers_async.create_channel( 

174 host, 

175 credentials=credentials, 

176 credentials_file=credentials_file, 

177 quota_project_id=quota_project_id, 

178 default_scopes=cls.AUTH_SCOPES, 

179 scopes=scopes, 

180 default_host=cls.DEFAULT_HOST, 

181 **kwargs, 

182 ) 

183 

184 def __init__( 

185 self, 

186 *, 

187 host: str = "iamcredentials.googleapis.com", 

188 credentials: Optional[ga_credentials.Credentials] = None, 

189 credentials_file: Optional[str] = None, 

190 scopes: Optional[Sequence[str]] = None, 

191 channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, 

192 api_mtls_endpoint: Optional[str] = None, 

193 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

194 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, 

195 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

196 quota_project_id: Optional[str] = None, 

197 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

198 always_use_jwt_access: Optional[bool] = False, 

199 api_audience: Optional[str] = None, 

200 ) -> None: 

201 """Instantiate the transport. 

202 

203 Args: 

204 host (Optional[str]): 

205 The hostname to connect to (default: 'iamcredentials.googleapis.com'). 

206 credentials (Optional[google.auth.credentials.Credentials]): The 

207 authorization credentials to attach to requests. These 

208 credentials identify the application to the service; if none 

209 are specified, the client will attempt to ascertain the 

210 credentials from the environment. 

211 This argument is ignored if a ``channel`` instance is provided. 

212 credentials_file (Optional[str]): Deprecated. A file with credentials that can 

213 be loaded with :func:`google.auth.load_credentials_from_file`. 

214 This argument is ignored if a ``channel`` instance is provided. 

215 This argument will be removed in the next major version of this library. 

216 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this 

217 service. These are only used when credentials are not specified and 

218 are passed to :func:`google.auth.default`. 

219 channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): 

220 A ``Channel`` instance through which to make calls, or a Callable 

221 that constructs and returns one. If set to None, ``self.create_channel`` 

222 is used to create the channel. If a Callable is given, it will be called 

223 with the same arguments as used in ``self.create_channel``. 

224 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. 

225 If provided, it overrides the ``host`` argument and tries to create 

226 a mutual TLS channel with client SSL credentials from 

227 ``client_cert_source`` or application default SSL credentials. 

228 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 

229 Deprecated. A callback to provide client SSL certificate bytes and 

230 private key bytes, both in PEM format. It is ignored if 

231 ``api_mtls_endpoint`` is None. 

232 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials 

233 for the grpc channel. It is ignored if a ``channel`` instance is provided. 

234 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): 

235 A callback to provide client certificate bytes and private key bytes, 

236 both in PEM format. It is used to configure a mutual TLS channel. It is 

237 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. 

238 quota_project_id (Optional[str]): An optional project to use for billing 

239 and quota. 

240 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

241 The client info used to send a user-agent string along with 

242 API requests. If ``None``, then default info will be used. 

243 Generally, you only need to set this if you're developing 

244 your own client library. 

245 always_use_jwt_access (Optional[bool]): Whether self signed JWT should 

246 be used for service account credentials. 

247 api_audience (Optional[str]): The intended audience for the API calls 

248 to the service that will be set when using certain 3rd party 

249 authentication flows. Audience is typically a resource identifier. 

250 If not set, the host value will be used as a default. 

251 

252 Raises: 

253 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 

254 creation failed for any reason. 

255 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` 

256 and ``credentials_file`` are passed. 

257 """ 

258 self._grpc_channel = None 

259 self._ssl_channel_credentials = ssl_channel_credentials 

260 self._stubs: Dict[str, Callable] = {} 

261 

262 if api_mtls_endpoint: 

263 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 

264 if client_cert_source: 

265 warnings.warn("client_cert_source is deprecated", DeprecationWarning) 

266 

267 if isinstance(channel, aio.Channel): 

268 # Ignore credentials if a channel was passed. 

269 credentials = None 

270 self._ignore_credentials = True 

271 # If a channel was explicitly provided, set it. 

272 self._grpc_channel = channel 

273 self._ssl_channel_credentials = None 

274 else: 

275 if api_mtls_endpoint: 

276 host = api_mtls_endpoint 

277 

278 # Create SSL credentials with client_cert_source or application 

279 # default SSL credentials. 

280 if client_cert_source: 

281 cert, key = client_cert_source() 

282 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

283 certificate_chain=cert, private_key=key 

284 ) 

285 else: 

286 self._ssl_channel_credentials = SslCredentials().ssl_credentials 

287 

288 else: 

289 if client_cert_source_for_mtls and not ssl_channel_credentials: 

290 cert, key = client_cert_source_for_mtls() 

291 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

292 certificate_chain=cert, private_key=key 

293 ) 

294 

295 # The base transport sets the host, credentials and scopes 

296 super().__init__( 

297 host=host, 

298 credentials=credentials, 

299 credentials_file=credentials_file, 

300 scopes=scopes, 

301 quota_project_id=quota_project_id, 

302 client_info=client_info, 

303 always_use_jwt_access=always_use_jwt_access, 

304 api_audience=api_audience, 

305 ) 

306 

307 if not self._grpc_channel: 

308 # initialize with the provided callable or the default channel 

309 channel_init = channel or type(self).create_channel 

310 self._grpc_channel = channel_init( 

311 self._host, 

312 # use the credentials which are saved 

313 credentials=self._credentials, 

314 # Set ``credentials_file`` to ``None`` here as 

315 # the credentials that we saved earlier should be used. 

316 credentials_file=None, 

317 scopes=self._scopes, 

318 ssl_credentials=self._ssl_channel_credentials, 

319 quota_project_id=quota_project_id, 

320 options=[ 

321 ("grpc.max_send_message_length", -1), 

322 ("grpc.max_receive_message_length", -1), 

323 ], 

324 ) 

325 

326 self._interceptor = _LoggingClientAIOInterceptor() 

327 self._grpc_channel._unary_unary_interceptors.append(self._interceptor) 

328 self._logged_channel = self._grpc_channel 

329 self._wrap_with_kind = ( 

330 "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters 

331 ) 

332 # Wrap messages. This must be done after self._logged_channel exists 

333 self._prep_wrapped_messages(client_info) 

334 

335 @property 

336 def grpc_channel(self) -> aio.Channel: 

337 """Create the channel designed to connect to this service. 

338 

339 This property caches on the instance; repeated calls return 

340 the same channel. 

341 """ 

342 # Return the channel from cache. 

343 return self._grpc_channel 

344 

345 @property 

346 def generate_access_token( 

347 self, 

348 ) -> Callable[ 

349 [common.GenerateAccessTokenRequest], 

350 Awaitable[common.GenerateAccessTokenResponse], 

351 ]: 

352 r"""Return a callable for the generate access token method over gRPC. 

353 

354 Generates an OAuth 2.0 access token for a service 

355 account. 

356 

357 Returns: 

358 Callable[[~.GenerateAccessTokenRequest], 

359 Awaitable[~.GenerateAccessTokenResponse]]: 

360 A function that, when called, will call the underlying RPC 

361 on the server. 

362 """ 

363 # Generate a "stub function" on-the-fly which will actually make 

364 # the request. 

365 # gRPC handles serialization and deserialization, so we just need 

366 # to pass in the functions for each. 

367 if "generate_access_token" not in self._stubs: 

368 self._stubs["generate_access_token"] = self._logged_channel.unary_unary( 

369 "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", 

370 request_serializer=common.GenerateAccessTokenRequest.serialize, 

371 response_deserializer=common.GenerateAccessTokenResponse.deserialize, 

372 ) 

373 return self._stubs["generate_access_token"] 

374 

375 @property 

376 def generate_id_token( 

377 self, 

378 ) -> Callable[ 

379 [common.GenerateIdTokenRequest], Awaitable[common.GenerateIdTokenResponse] 

380 ]: 

381 r"""Return a callable for the generate id token method over gRPC. 

382 

383 Generates an OpenID Connect ID token for a service 

384 account. 

385 

386 Returns: 

387 Callable[[~.GenerateIdTokenRequest], 

388 Awaitable[~.GenerateIdTokenResponse]]: 

389 A function that, when called, will call the underlying RPC 

390 on the server. 

391 """ 

392 # Generate a "stub function" on-the-fly which will actually make 

393 # the request. 

394 # gRPC handles serialization and deserialization, so we just need 

395 # to pass in the functions for each. 

396 if "generate_id_token" not in self._stubs: 

397 self._stubs["generate_id_token"] = self._logged_channel.unary_unary( 

398 "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", 

399 request_serializer=common.GenerateIdTokenRequest.serialize, 

400 response_deserializer=common.GenerateIdTokenResponse.deserialize, 

401 ) 

402 return self._stubs["generate_id_token"] 

403 

404 @property 

405 def sign_blob( 

406 self, 

407 ) -> Callable[[common.SignBlobRequest], Awaitable[common.SignBlobResponse]]: 

408 r"""Return a callable for the sign blob method over gRPC. 

409 

410 Signs a blob using a service account's system-managed 

411 private key. 

412 

413 Returns: 

414 Callable[[~.SignBlobRequest], 

415 Awaitable[~.SignBlobResponse]]: 

416 A function that, when called, will call the underlying RPC 

417 on the server. 

418 """ 

419 # Generate a "stub function" on-the-fly which will actually make 

420 # the request. 

421 # gRPC handles serialization and deserialization, so we just need 

422 # to pass in the functions for each. 

423 if "sign_blob" not in self._stubs: 

424 self._stubs["sign_blob"] = self._logged_channel.unary_unary( 

425 "/google.iam.credentials.v1.IAMCredentials/SignBlob", 

426 request_serializer=common.SignBlobRequest.serialize, 

427 response_deserializer=common.SignBlobResponse.deserialize, 

428 ) 

429 return self._stubs["sign_blob"] 

430 

431 @property 

432 def sign_jwt( 

433 self, 

434 ) -> Callable[[common.SignJwtRequest], Awaitable[common.SignJwtResponse]]: 

435 r"""Return a callable for the sign jwt method over gRPC. 

436 

437 Signs a JWT using a service account's system-managed 

438 private key. 

439 

440 Returns: 

441 Callable[[~.SignJwtRequest], 

442 Awaitable[~.SignJwtResponse]]: 

443 A function that, when called, will call the underlying RPC 

444 on the server. 

445 """ 

446 # Generate a "stub function" on-the-fly which will actually make 

447 # the request. 

448 # gRPC handles serialization and deserialization, so we just need 

449 # to pass in the functions for each. 

450 if "sign_jwt" not in self._stubs: 

451 self._stubs["sign_jwt"] = self._logged_channel.unary_unary( 

452 "/google.iam.credentials.v1.IAMCredentials/SignJwt", 

453 request_serializer=common.SignJwtRequest.serialize, 

454 response_deserializer=common.SignJwtResponse.deserialize, 

455 ) 

456 return self._stubs["sign_jwt"] 

457 

458 def _prep_wrapped_messages(self, client_info): 

459 """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" 

460 self._wrapped_methods = { 

461 self.generate_access_token: self._wrap_method( 

462 self.generate_access_token, 

463 default_retry=retries.AsyncRetry( 

464 initial=0.1, 

465 maximum=60.0, 

466 multiplier=1.3, 

467 predicate=retries.if_exception_type( 

468 core_exceptions.DeadlineExceeded, 

469 core_exceptions.ServiceUnavailable, 

470 ), 

471 deadline=60.0, 

472 ), 

473 default_timeout=60.0, 

474 client_info=client_info, 

475 ), 

476 self.generate_id_token: self._wrap_method( 

477 self.generate_id_token, 

478 default_retry=retries.AsyncRetry( 

479 initial=0.1, 

480 maximum=60.0, 

481 multiplier=1.3, 

482 predicate=retries.if_exception_type( 

483 core_exceptions.DeadlineExceeded, 

484 core_exceptions.ServiceUnavailable, 

485 ), 

486 deadline=60.0, 

487 ), 

488 default_timeout=60.0, 

489 client_info=client_info, 

490 ), 

491 self.sign_blob: self._wrap_method( 

492 self.sign_blob, 

493 default_retry=retries.AsyncRetry( 

494 initial=0.1, 

495 maximum=60.0, 

496 multiplier=1.3, 

497 predicate=retries.if_exception_type( 

498 core_exceptions.DeadlineExceeded, 

499 core_exceptions.ServiceUnavailable, 

500 ), 

501 deadline=60.0, 

502 ), 

503 default_timeout=60.0, 

504 client_info=client_info, 

505 ), 

506 self.sign_jwt: self._wrap_method( 

507 self.sign_jwt, 

508 default_retry=retries.AsyncRetry( 

509 initial=0.1, 

510 maximum=60.0, 

511 multiplier=1.3, 

512 predicate=retries.if_exception_type( 

513 core_exceptions.DeadlineExceeded, 

514 core_exceptions.ServiceUnavailable, 

515 ), 

516 deadline=60.0, 

517 ), 

518 default_timeout=60.0, 

519 client_info=client_info, 

520 ), 

521 } 

522 

523 def _wrap_method(self, func, *args, **kwargs): 

524 if self._wrap_with_kind: # pragma: NO COVER 

525 kwargs["kind"] = self.kind 

526 return gapic_v1.method_async.wrap_method(func, *args, **kwargs) 

527 

528 def close(self): 

529 return self._logged_channel.close() 

530 

531 @property 

532 def kind(self) -> str: 

533 return "grpc_asyncio" 

534 

535 

536__all__ = ("IAMCredentialsGrpcAsyncIOTransport",)