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 

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

21import warnings 

22 

23from google.api_core import exceptions as core_exceptions 

24from google.api_core import gapic_v1, grpc_helpers_async 

25from google.api_core import retry_async as retries 

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

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

28from google.protobuf.json_format import MessageToJson 

29import google.protobuf.message 

30import grpc # type: ignore 

31from grpc.experimental import aio # type: ignore 

32import proto # 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)}" 

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)}" 

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 

248 Raises: 

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

250 creation failed for any reason. 

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

252 and ``credentials_file`` are passed. 

253 """ 

254 self._grpc_channel = None 

255 self._ssl_channel_credentials = ssl_channel_credentials 

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

257 

258 if api_mtls_endpoint: 

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

260 if client_cert_source: 

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

262 

263 if isinstance(channel, aio.Channel): 

264 # Ignore credentials if a channel was passed. 

265 credentials = None 

266 self._ignore_credentials = True 

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

268 self._grpc_channel = channel 

269 self._ssl_channel_credentials = None 

270 else: 

271 if api_mtls_endpoint: 

272 host = api_mtls_endpoint 

273 

274 # Create SSL credentials with client_cert_source or application 

275 # default SSL credentials. 

276 if client_cert_source: 

277 cert, key = client_cert_source() 

278 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

279 certificate_chain=cert, private_key=key 

280 ) 

281 else: 

282 self._ssl_channel_credentials = SslCredentials().ssl_credentials 

283 

284 else: 

285 if client_cert_source_for_mtls and not ssl_channel_credentials: 

286 cert, key = client_cert_source_for_mtls() 

287 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

288 certificate_chain=cert, private_key=key 

289 ) 

290 

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

292 super().__init__( 

293 host=host, 

294 credentials=credentials, 

295 credentials_file=credentials_file, 

296 scopes=scopes, 

297 quota_project_id=quota_project_id, 

298 client_info=client_info, 

299 always_use_jwt_access=always_use_jwt_access, 

300 api_audience=api_audience, 

301 ) 

302 

303 if not self._grpc_channel: 

304 # initialize with the provided callable or the default channel 

305 channel_init = channel or type(self).create_channel 

306 self._grpc_channel = channel_init( 

307 self._host, 

308 # use the credentials which are saved 

309 credentials=self._credentials, 

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

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

312 credentials_file=None, 

313 scopes=self._scopes, 

314 ssl_credentials=self._ssl_channel_credentials, 

315 quota_project_id=quota_project_id, 

316 options=[ 

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

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

319 ], 

320 ) 

321 

322 self._interceptor = _LoggingClientAIOInterceptor() 

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

324 self._logged_channel = self._grpc_channel 

325 self._wrap_with_kind = ( 

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

327 ) 

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

329 self._prep_wrapped_messages(client_info) 

330 

331 @property 

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

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

334 

335 This property caches on the instance; repeated calls return 

336 the same channel. 

337 """ 

338 # Return the channel from cache. 

339 return self._grpc_channel 

340 

341 @property 

342 def generate_access_token( 

343 self, 

344 ) -> Callable[ 

345 [common.GenerateAccessTokenRequest], 

346 Awaitable[common.GenerateAccessTokenResponse], 

347 ]: 

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

349 

350 Generates an OAuth 2.0 access token for a service 

351 account. 

352 

353 Returns: 

354 Callable[[~.GenerateAccessTokenRequest], 

355 Awaitable[~.GenerateAccessTokenResponse]]: 

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

357 on the server. 

358 """ 

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

360 # the request. 

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

362 # to pass in the functions for each. 

363 if "generate_access_token" not in self._stubs: 

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

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

366 request_serializer=common.GenerateAccessTokenRequest.serialize, 

367 response_deserializer=common.GenerateAccessTokenResponse.deserialize, 

368 ) 

369 return self._stubs["generate_access_token"] 

370 

371 @property 

372 def generate_id_token( 

373 self, 

374 ) -> Callable[ 

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

376 ]: 

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

378 

379 Generates an OpenID Connect ID token for a service 

380 account. 

381 

382 Returns: 

383 Callable[[~.GenerateIdTokenRequest], 

384 Awaitable[~.GenerateIdTokenResponse]]: 

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

386 on the server. 

387 """ 

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

389 # the request. 

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

391 # to pass in the functions for each. 

392 if "generate_id_token" not in self._stubs: 

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

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

395 request_serializer=common.GenerateIdTokenRequest.serialize, 

396 response_deserializer=common.GenerateIdTokenResponse.deserialize, 

397 ) 

398 return self._stubs["generate_id_token"] 

399 

400 @property 

401 def sign_blob( 

402 self, 

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

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

405 

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

407 private key. 

408 

409 Returns: 

410 Callable[[~.SignBlobRequest], 

411 Awaitable[~.SignBlobResponse]]: 

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

413 on the server. 

414 """ 

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

416 # the request. 

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

418 # to pass in the functions for each. 

419 if "sign_blob" not in self._stubs: 

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

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

422 request_serializer=common.SignBlobRequest.serialize, 

423 response_deserializer=common.SignBlobResponse.deserialize, 

424 ) 

425 return self._stubs["sign_blob"] 

426 

427 @property 

428 def sign_jwt( 

429 self, 

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

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

432 

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

434 private key. 

435 

436 Returns: 

437 Callable[[~.SignJwtRequest], 

438 Awaitable[~.SignJwtResponse]]: 

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

440 on the server. 

441 """ 

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

443 # the request. 

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

445 # to pass in the functions for each. 

446 if "sign_jwt" not in self._stubs: 

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

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

449 request_serializer=common.SignJwtRequest.serialize, 

450 response_deserializer=common.SignJwtResponse.deserialize, 

451 ) 

452 return self._stubs["sign_jwt"] 

453 

454 def _prep_wrapped_messages(self, client_info): 

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

456 self._wrapped_methods = { 

457 self.generate_access_token: self._wrap_method( 

458 self.generate_access_token, 

459 default_retry=retries.AsyncRetry( 

460 initial=0.1, 

461 maximum=60.0, 

462 multiplier=1.3, 

463 predicate=retries.if_exception_type( 

464 core_exceptions.DeadlineExceeded, 

465 core_exceptions.ServiceUnavailable, 

466 ), 

467 deadline=60.0, 

468 ), 

469 default_timeout=60.0, 

470 client_info=client_info, 

471 ), 

472 self.generate_id_token: self._wrap_method( 

473 self.generate_id_token, 

474 default_retry=retries.AsyncRetry( 

475 initial=0.1, 

476 maximum=60.0, 

477 multiplier=1.3, 

478 predicate=retries.if_exception_type( 

479 core_exceptions.DeadlineExceeded, 

480 core_exceptions.ServiceUnavailable, 

481 ), 

482 deadline=60.0, 

483 ), 

484 default_timeout=60.0, 

485 client_info=client_info, 

486 ), 

487 self.sign_blob: self._wrap_method( 

488 self.sign_blob, 

489 default_retry=retries.AsyncRetry( 

490 initial=0.1, 

491 maximum=60.0, 

492 multiplier=1.3, 

493 predicate=retries.if_exception_type( 

494 core_exceptions.DeadlineExceeded, 

495 core_exceptions.ServiceUnavailable, 

496 ), 

497 deadline=60.0, 

498 ), 

499 default_timeout=60.0, 

500 client_info=client_info, 

501 ), 

502 self.sign_jwt: self._wrap_method( 

503 self.sign_jwt, 

504 default_retry=retries.AsyncRetry( 

505 initial=0.1, 

506 maximum=60.0, 

507 multiplier=1.3, 

508 predicate=retries.if_exception_type( 

509 core_exceptions.DeadlineExceeded, 

510 core_exceptions.ServiceUnavailable, 

511 ), 

512 deadline=60.0, 

513 ), 

514 default_timeout=60.0, 

515 client_info=client_info, 

516 ), 

517 } 

518 

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

520 if self._wrap_with_kind: # pragma: NO COVER 

521 kwargs["kind"] = self.kind 

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

523 

524 def close(self): 

525 return self._logged_channel.close() 

526 

527 @property 

528 def kind(self) -> str: 

529 return "grpc_asyncio" 

530 

531 

532__all__ = ("IAMCredentialsGrpcAsyncIOTransport",)