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

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

148 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 logging as std_logging 

17import re 

18from collections import OrderedDict 

19from typing import ( 

20 Callable, 

21 Dict, 

22 Mapping, 

23 MutableMapping, 

24 MutableSequence, 

25 Optional, 

26 Sequence, 

27 Tuple, 

28 Type, 

29 Union, 

30) 

31 

32import google.protobuf 

33from google.api_core import exceptions as core_exceptions 

34from google.api_core import gapic_v1 

35from google.api_core import retry_async as retries 

36from google.api_core.client_options import ClientOptions 

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

38from google.oauth2 import service_account # type: ignore 

39 

40from google.cloud.iam_credentials_v1 import gapic_version as package_version 

41 

42try: 

43 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] 

44except AttributeError: # pragma: NO COVER 

45 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore 

46 

47import google.protobuf.duration_pb2 as duration_pb2 # type: ignore 

48import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore 

49 

50from google.cloud.iam_credentials_v1.types import common 

51 

52from .client import IAMCredentialsClient 

53from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport 

54from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport 

55 

56try: 

57 from google.api_core import client_logging # type: ignore 

58 

59 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

60except ImportError: # pragma: NO COVER 

61 CLIENT_LOGGING_SUPPORTED = False 

62 

63_LOGGER = std_logging.getLogger(__name__) 

64 

65 

66class IAMCredentialsAsyncClient: 

67 """A service account is a special type of Google account that 

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

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

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

71 users aren't directly involved. 

72 

73 Service account credentials are used to temporarily assume the 

74 identity of the service account. Supported credential types 

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

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

77 """ 

78 

79 _client: IAMCredentialsClient 

80 

81 # Copy defaults from the synchronous client for use here. 

82 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. 

83 DEFAULT_ENDPOINT = IAMCredentialsClient.DEFAULT_ENDPOINT 

84 DEFAULT_MTLS_ENDPOINT = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT 

85 _DEFAULT_ENDPOINT_TEMPLATE = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE 

86 _DEFAULT_UNIVERSE = IAMCredentialsClient._DEFAULT_UNIVERSE 

87 

88 service_account_path = staticmethod(IAMCredentialsClient.service_account_path) 

89 parse_service_account_path = staticmethod( 

90 IAMCredentialsClient.parse_service_account_path 

91 ) 

92 common_billing_account_path = staticmethod( 

93 IAMCredentialsClient.common_billing_account_path 

94 ) 

95 parse_common_billing_account_path = staticmethod( 

96 IAMCredentialsClient.parse_common_billing_account_path 

97 ) 

98 common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path) 

99 parse_common_folder_path = staticmethod( 

100 IAMCredentialsClient.parse_common_folder_path 

101 ) 

102 common_organization_path = staticmethod( 

103 IAMCredentialsClient.common_organization_path 

104 ) 

105 parse_common_organization_path = staticmethod( 

106 IAMCredentialsClient.parse_common_organization_path 

107 ) 

108 common_project_path = staticmethod(IAMCredentialsClient.common_project_path) 

109 parse_common_project_path = staticmethod( 

110 IAMCredentialsClient.parse_common_project_path 

111 ) 

112 common_location_path = staticmethod(IAMCredentialsClient.common_location_path) 

113 parse_common_location_path = staticmethod( 

114 IAMCredentialsClient.parse_common_location_path 

115 ) 

116 

117 @classmethod 

118 def from_service_account_info(cls, info: dict, *args, **kwargs): 

119 """Creates an instance of this client using the provided credentials 

120 info. 

121 

122 Args: 

123 info (dict): The service account private key info. 

124 args: Additional arguments to pass to the constructor. 

125 kwargs: Additional arguments to pass to the constructor. 

126 

127 Returns: 

128 IAMCredentialsAsyncClient: The constructed client. 

129 """ 

130 sa_info_func = ( 

131 IAMCredentialsClient.from_service_account_info.__func__ # type: ignore 

132 ) 

133 return sa_info_func(IAMCredentialsAsyncClient, info, *args, **kwargs) 

134 

135 @classmethod 

136 def from_service_account_file(cls, filename: str, *args, **kwargs): 

137 """Creates an instance of this client using the provided credentials 

138 file. 

139 

140 Args: 

141 filename (str): The path to the service account private key json 

142 file. 

143 args: Additional arguments to pass to the constructor. 

144 kwargs: Additional arguments to pass to the constructor. 

145 

146 Returns: 

147 IAMCredentialsAsyncClient: The constructed client. 

148 """ 

149 sa_file_func = ( 

150 IAMCredentialsClient.from_service_account_file.__func__ # type: ignore 

151 ) 

152 return sa_file_func(IAMCredentialsAsyncClient, filename, *args, **kwargs) 

153 

154 from_service_account_json = from_service_account_file 

155 

156 @classmethod 

157 def get_mtls_endpoint_and_cert_source( 

158 cls, client_options: Optional[ClientOptions] = None 

159 ): 

160 """Return the API endpoint and client cert source for mutual TLS. 

161 

162 The client cert source is determined in the following order: 

163 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

164 client cert source is None. 

165 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

166 default client cert source exists, use the default one; otherwise the client cert 

167 source is None. 

168 

169 The API endpoint is determined in the following order: 

170 (1) if `client_options.api_endpoint` if provided, use the provided one. 

171 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

172 default mTLS endpoint; if the environment variable is "never", use the default API 

173 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

174 use the default API endpoint. 

175 

176 More details can be found at https://google.aip.dev/auth/4114. 

177 

178 Args: 

179 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

180 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

181 in this method. 

182 

183 Returns: 

184 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

185 client cert source to use. 

186 

187 Raises: 

188 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

189 """ 

190 return IAMCredentialsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore 

191 

192 @property 

193 def transport(self) -> IAMCredentialsTransport: 

194 """Returns the transport used by the client instance. 

195 

196 Returns: 

197 IAMCredentialsTransport: The transport used by the client instance. 

198 """ 

199 return self._client.transport 

200 

201 @property 

202 def api_endpoint(self) -> str: 

203 """Return the API endpoint used by the client instance. 

204 

205 Returns: 

206 str: The API endpoint used by the client instance. 

207 """ 

208 return self._client._api_endpoint 

209 

210 @property 

211 def universe_domain(self) -> str: 

212 """Return the universe domain used by the client instance. 

213 

214 Returns: 

215 str: The universe domain used 

216 by the client instance. 

217 """ 

218 return self._client._universe_domain 

219 

220 get_transport_class = IAMCredentialsClient.get_transport_class 

221 

222 def __init__( 

223 self, 

224 *, 

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

226 transport: Optional[ 

227 Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] 

228 ] = "grpc_asyncio", 

229 client_options: Optional[ClientOptions] = None, 

230 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

231 ) -> None: 

232 """Instantiates the iam credentials async client. 

233 

234 Args: 

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

236 authorization credentials to attach to requests. These 

237 credentials identify the application to the service; if none 

238 are specified, the client will attempt to ascertain the 

239 credentials from the environment. 

240 transport (Optional[Union[str,IAMCredentialsTransport,Callable[..., IAMCredentialsTransport]]]): 

241 The transport to use, or a Callable that constructs and returns a new transport to use. 

242 If a Callable is given, it will be called with the same set of initialization 

243 arguments as used in the IAMCredentialsTransport constructor. 

244 If set to None, a transport is chosen automatically. 

245 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

246 Custom options for the client. 

247 

248 1. The ``api_endpoint`` property can be used to override the 

249 default endpoint provided by the client when ``transport`` is 

250 not explicitly provided. Only if this property is not set and 

251 ``transport`` was not explicitly provided, the endpoint is 

252 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

253 variable, which have one of the following values: 

254 "always" (always use the default mTLS endpoint), "never" (always 

255 use the default regular endpoint) and "auto" (auto-switch to the 

256 default mTLS endpoint if client certificate is present; this is 

257 the default value). 

258 

259 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

260 is "true", then the ``client_cert_source`` property can be used 

261 to provide a client certificate for mTLS transport. If 

262 not provided, the default SSL client certificate will be used if 

263 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

264 set, no client certificate will be used. 

265 

266 3. The ``universe_domain`` property can be used to override the 

267 default "googleapis.com" universe. Note that ``api_endpoint`` 

268 property still takes precedence; and ``universe_domain`` is 

269 currently not supported for mTLS. 

270 

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

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

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

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

275 your own client library. 

276 

277 Raises: 

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

279 creation failed for any reason. 

280 """ 

281 self._client = IAMCredentialsClient( 

282 credentials=credentials, 

283 transport=transport, 

284 client_options=client_options, 

285 client_info=client_info, 

286 ) 

287 

288 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

289 std_logging.DEBUG 

290 ): # pragma: NO COVER 

291 _LOGGER.debug( 

292 "Created client `google.iam.credentials_v1.IAMCredentialsAsyncClient`.", 

293 extra={ 

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

295 "universeDomain": getattr( 

296 self._client._transport._credentials, "universe_domain", "" 

297 ), 

298 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", 

299 "credentialsInfo": getattr( 

300 self.transport._credentials, "get_cred_info", lambda: None 

301 )(), 

302 } 

303 if hasattr(self._client._transport, "_credentials") 

304 else { 

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

306 "credentialsType": None, 

307 }, 

308 ) 

309 

310 async def generate_access_token( 

311 self, 

312 request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, 

313 *, 

314 name: Optional[str] = None, 

315 delegates: Optional[MutableSequence[str]] = None, 

316 scope: Optional[MutableSequence[str]] = None, 

317 lifetime: Optional[duration_pb2.Duration] = None, 

318 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

319 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

320 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

321 ) -> common.GenerateAccessTokenResponse: 

322 r"""Generates an OAuth 2.0 access token for a service 

323 account. 

324 

325 .. code-block:: python 

326 

327 # This snippet has been automatically generated and should be regarded as a 

328 # code template only. 

329 # It will require modifications to work: 

330 # - It may require correct/in-range values for request initialization. 

331 # - It may require specifying regional endpoints when creating the service 

332 # client as shown in: 

333 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

334 from google.cloud import iam_credentials_v1 

335 

336 async def sample_generate_access_token(): 

337 # Create a client 

338 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

339 

340 # Initialize request argument(s) 

341 request = iam_credentials_v1.GenerateAccessTokenRequest( 

342 name="name_value", 

343 scope=['scope_value1', 'scope_value2'], 

344 ) 

345 

346 # Make the request 

347 response = await client.generate_access_token(request=request) 

348 

349 # Handle the response 

350 print(response) 

351 

352 Args: 

353 request (Optional[Union[google.cloud.iam_credentials_v1.types.GenerateAccessTokenRequest, dict]]): 

354 The request object. 

355 name (:class:`str`): 

356 Required. The resource name of the service account for 

357 which the credentials are requested, in the following 

358 format: 

359 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

360 The ``-`` wildcard character is required; replacing it 

361 with a project ID is invalid. 

362 

363 This corresponds to the ``name`` field 

364 on the ``request`` instance; if ``request`` is provided, this 

365 should not be set. 

366 delegates (:class:`MutableSequence[str]`): 

367 The sequence of service accounts in a delegation chain. 

368 Each service account must be granted the 

369 ``roles/iam.serviceAccountTokenCreator`` role on its 

370 next service account in the chain. The last service 

371 account in the chain must be granted the 

372 ``roles/iam.serviceAccountTokenCreator`` role on the 

373 service account that is specified in the ``name`` field 

374 of the request. 

375 

376 The delegates must have the following format: 

377 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

378 The ``-`` wildcard character is required; replacing it 

379 with a project ID is invalid. 

380 

381 This corresponds to the ``delegates`` field 

382 on the ``request`` instance; if ``request`` is provided, this 

383 should not be set. 

384 scope (:class:`MutableSequence[str]`): 

385 Required. Code to identify the scopes 

386 to be included in the OAuth 2.0 access 

387 token. See 

388 https://developers.google.com/identity/protocols/googlescopes 

389 for more information. 

390 At least one value required. 

391 

392 This corresponds to the ``scope`` field 

393 on the ``request`` instance; if ``request`` is provided, this 

394 should not be set. 

395 lifetime (:class:`google.protobuf.duration_pb2.Duration`): 

396 The desired lifetime duration of the 

397 access token in seconds. Must be set to 

398 a value less than or equal to 3600 (1 

399 hour). If a value is not specified, the 

400 token's lifetime will be set to a 

401 default value of one hour. 

402 

403 This corresponds to the ``lifetime`` field 

404 on the ``request`` instance; if ``request`` is provided, this 

405 should not be set. 

406 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

407 should be retried. 

408 timeout (float): The timeout for this request. 

409 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

410 sent along with the request as metadata. Normally, each value must be of type `str`, 

411 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

412 be of type `bytes`. 

413 

414 Returns: 

415 google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse: 

416 

417 """ 

418 # Create or coerce a protobuf request object. 

419 # - Quick check: If we got a request object, we should *not* have 

420 # gotten any keyword arguments that map to the request. 

421 flattened_params = [name, delegates, scope, lifetime] 

422 has_flattened_params = ( 

423 len([param for param in flattened_params if param is not None]) > 0 

424 ) 

425 if request is not None and has_flattened_params: 

426 raise ValueError( 

427 "If the `request` argument is set, then none of " 

428 "the individual field arguments should be set." 

429 ) 

430 

431 # - Use the request object if provided (there's no risk of modifying the input as 

432 # there are no flattened fields), or create one. 

433 if not isinstance(request, common.GenerateAccessTokenRequest): 

434 request = common.GenerateAccessTokenRequest(request) 

435 

436 # If we have keyword arguments corresponding to fields on the 

437 # request, apply these. 

438 if name is not None: 

439 request.name = name 

440 if lifetime is not None: 

441 request.lifetime = lifetime 

442 if delegates: 

443 request.delegates.extend(delegates) 

444 if scope: 

445 request.scope.extend(scope) 

446 

447 # Wrap the RPC method; this adds retry and timeout information, 

448 # and friendly error handling. 

449 rpc = self._client._transport._wrapped_methods[ 

450 self._client._transport.generate_access_token 

451 ] 

452 

453 # Certain fields should be provided within the metadata header; 

454 # add these here. 

455 metadata = tuple(metadata) + ( 

456 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

457 ) 

458 

459 # Validate the universe domain. 

460 self._client._validate_universe_domain() 

461 

462 # Send the request. 

463 response = await rpc( 

464 request, 

465 retry=retry, 

466 timeout=timeout, 

467 metadata=metadata, 

468 ) 

469 

470 # Done; return the response. 

471 return response 

472 

473 async def generate_id_token( 

474 self, 

475 request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, 

476 *, 

477 name: Optional[str] = None, 

478 delegates: Optional[MutableSequence[str]] = None, 

479 audience: Optional[str] = None, 

480 include_email: Optional[bool] = None, 

481 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

482 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

483 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

484 ) -> common.GenerateIdTokenResponse: 

485 r"""Generates an OpenID Connect ID token for a service 

486 account. 

487 

488 .. code-block:: python 

489 

490 # This snippet has been automatically generated and should be regarded as a 

491 # code template only. 

492 # It will require modifications to work: 

493 # - It may require correct/in-range values for request initialization. 

494 # - It may require specifying regional endpoints when creating the service 

495 # client as shown in: 

496 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

497 from google.cloud import iam_credentials_v1 

498 

499 async def sample_generate_id_token(): 

500 # Create a client 

501 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

502 

503 # Initialize request argument(s) 

504 request = iam_credentials_v1.GenerateIdTokenRequest( 

505 name="name_value", 

506 audience="audience_value", 

507 ) 

508 

509 # Make the request 

510 response = await client.generate_id_token(request=request) 

511 

512 # Handle the response 

513 print(response) 

514 

515 Args: 

516 request (Optional[Union[google.cloud.iam_credentials_v1.types.GenerateIdTokenRequest, dict]]): 

517 The request object. 

518 name (:class:`str`): 

519 Required. The resource name of the service account for 

520 which the credentials are requested, in the following 

521 format: 

522 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

523 The ``-`` wildcard character is required; replacing it 

524 with a project ID is invalid. 

525 

526 This corresponds to the ``name`` field 

527 on the ``request`` instance; if ``request`` is provided, this 

528 should not be set. 

529 delegates (:class:`MutableSequence[str]`): 

530 The sequence of service accounts in a delegation chain. 

531 Each service account must be granted the 

532 ``roles/iam.serviceAccountTokenCreator`` role on its 

533 next service account in the chain. The last service 

534 account in the chain must be granted the 

535 ``roles/iam.serviceAccountTokenCreator`` role on the 

536 service account that is specified in the ``name`` field 

537 of the request. 

538 

539 The delegates must have the following format: 

540 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

541 The ``-`` wildcard character is required; replacing it 

542 with a project ID is invalid. 

543 

544 This corresponds to the ``delegates`` field 

545 on the ``request`` instance; if ``request`` is provided, this 

546 should not be set. 

547 audience (:class:`str`): 

548 Required. The audience for the token, 

549 such as the API or account that this 

550 token grants access to. 

551 

552 This corresponds to the ``audience`` field 

553 on the ``request`` instance; if ``request`` is provided, this 

554 should not be set. 

555 include_email (:class:`bool`): 

556 Include the service account email in the token. If set 

557 to ``true``, the token will contain ``email`` and 

558 ``email_verified`` claims. 

559 

560 This corresponds to the ``include_email`` field 

561 on the ``request`` instance; if ``request`` is provided, this 

562 should not be set. 

563 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

564 should be retried. 

565 timeout (float): The timeout for this request. 

566 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

567 sent along with the request as metadata. Normally, each value must be of type `str`, 

568 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

569 be of type `bytes`. 

570 

571 Returns: 

572 google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse: 

573 

574 """ 

575 # Create or coerce a protobuf request object. 

576 # - Quick check: If we got a request object, we should *not* have 

577 # gotten any keyword arguments that map to the request. 

578 flattened_params = [name, delegates, audience, include_email] 

579 has_flattened_params = ( 

580 len([param for param in flattened_params if param is not None]) > 0 

581 ) 

582 if request is not None and has_flattened_params: 

583 raise ValueError( 

584 "If the `request` argument is set, then none of " 

585 "the individual field arguments should be set." 

586 ) 

587 

588 # - Use the request object if provided (there's no risk of modifying the input as 

589 # there are no flattened fields), or create one. 

590 if not isinstance(request, common.GenerateIdTokenRequest): 

591 request = common.GenerateIdTokenRequest(request) 

592 

593 # If we have keyword arguments corresponding to fields on the 

594 # request, apply these. 

595 if name is not None: 

596 request.name = name 

597 if audience is not None: 

598 request.audience = audience 

599 if include_email is not None: 

600 request.include_email = include_email 

601 if delegates: 

602 request.delegates.extend(delegates) 

603 

604 # Wrap the RPC method; this adds retry and timeout information, 

605 # and friendly error handling. 

606 rpc = self._client._transport._wrapped_methods[ 

607 self._client._transport.generate_id_token 

608 ] 

609 

610 # Certain fields should be provided within the metadata header; 

611 # add these here. 

612 metadata = tuple(metadata) + ( 

613 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

614 ) 

615 

616 # Validate the universe domain. 

617 self._client._validate_universe_domain() 

618 

619 # Send the request. 

620 response = await rpc( 

621 request, 

622 retry=retry, 

623 timeout=timeout, 

624 metadata=metadata, 

625 ) 

626 

627 # Done; return the response. 

628 return response 

629 

630 async def sign_blob( 

631 self, 

632 request: Optional[Union[common.SignBlobRequest, dict]] = None, 

633 *, 

634 name: Optional[str] = None, 

635 delegates: Optional[MutableSequence[str]] = None, 

636 payload: Optional[bytes] = None, 

637 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

638 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

639 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

640 ) -> common.SignBlobResponse: 

641 r"""Signs a blob using a service account's system-managed 

642 private key. 

643 

644 .. code-block:: python 

645 

646 # This snippet has been automatically generated and should be regarded as a 

647 # code template only. 

648 # It will require modifications to work: 

649 # - It may require correct/in-range values for request initialization. 

650 # - It may require specifying regional endpoints when creating the service 

651 # client as shown in: 

652 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

653 from google.cloud import iam_credentials_v1 

654 

655 async def sample_sign_blob(): 

656 # Create a client 

657 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

658 

659 # Initialize request argument(s) 

660 request = iam_credentials_v1.SignBlobRequest( 

661 name="name_value", 

662 payload=b'payload_blob', 

663 ) 

664 

665 # Make the request 

666 response = await client.sign_blob(request=request) 

667 

668 # Handle the response 

669 print(response) 

670 

671 Args: 

672 request (Optional[Union[google.cloud.iam_credentials_v1.types.SignBlobRequest, dict]]): 

673 The request object. 

674 name (:class:`str`): 

675 Required. The resource name of the service account for 

676 which the credentials are requested, in the following 

677 format: 

678 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

679 The ``-`` wildcard character is required; replacing it 

680 with a project ID is invalid. 

681 

682 This corresponds to the ``name`` field 

683 on the ``request`` instance; if ``request`` is provided, this 

684 should not be set. 

685 delegates (:class:`MutableSequence[str]`): 

686 The sequence of service accounts in a delegation chain. 

687 Each service account must be granted the 

688 ``roles/iam.serviceAccountTokenCreator`` role on its 

689 next service account in the chain. The last service 

690 account in the chain must be granted the 

691 ``roles/iam.serviceAccountTokenCreator`` role on the 

692 service account that is specified in the ``name`` field 

693 of the request. 

694 

695 The delegates must have the following format: 

696 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

697 The ``-`` wildcard character is required; replacing it 

698 with a project ID is invalid. 

699 

700 This corresponds to the ``delegates`` field 

701 on the ``request`` instance; if ``request`` is provided, this 

702 should not be set. 

703 payload (:class:`bytes`): 

704 Required. The bytes to sign. 

705 This corresponds to the ``payload`` field 

706 on the ``request`` instance; if ``request`` is provided, this 

707 should not be set. 

708 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

709 should be retried. 

710 timeout (float): The timeout for this request. 

711 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

712 sent along with the request as metadata. Normally, each value must be of type `str`, 

713 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

714 be of type `bytes`. 

715 

716 Returns: 

717 google.cloud.iam_credentials_v1.types.SignBlobResponse: 

718 

719 """ 

720 # Create or coerce a protobuf request object. 

721 # - Quick check: If we got a request object, we should *not* have 

722 # gotten any keyword arguments that map to the request. 

723 flattened_params = [name, delegates, payload] 

724 has_flattened_params = ( 

725 len([param for param in flattened_params if param is not None]) > 0 

726 ) 

727 if request is not None and has_flattened_params: 

728 raise ValueError( 

729 "If the `request` argument is set, then none of " 

730 "the individual field arguments should be set." 

731 ) 

732 

733 # - Use the request object if provided (there's no risk of modifying the input as 

734 # there are no flattened fields), or create one. 

735 if not isinstance(request, common.SignBlobRequest): 

736 request = common.SignBlobRequest(request) 

737 

738 # If we have keyword arguments corresponding to fields on the 

739 # request, apply these. 

740 if name is not None: 

741 request.name = name 

742 if payload is not None: 

743 request.payload = payload 

744 if delegates: 

745 request.delegates.extend(delegates) 

746 

747 # Wrap the RPC method; this adds retry and timeout information, 

748 # and friendly error handling. 

749 rpc = self._client._transport._wrapped_methods[ 

750 self._client._transport.sign_blob 

751 ] 

752 

753 # Certain fields should be provided within the metadata header; 

754 # add these here. 

755 metadata = tuple(metadata) + ( 

756 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

757 ) 

758 

759 # Validate the universe domain. 

760 self._client._validate_universe_domain() 

761 

762 # Send the request. 

763 response = await rpc( 

764 request, 

765 retry=retry, 

766 timeout=timeout, 

767 metadata=metadata, 

768 ) 

769 

770 # Done; return the response. 

771 return response 

772 

773 async def sign_jwt( 

774 self, 

775 request: Optional[Union[common.SignJwtRequest, dict]] = None, 

776 *, 

777 name: Optional[str] = None, 

778 delegates: Optional[MutableSequence[str]] = None, 

779 payload: Optional[str] = None, 

780 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

781 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

782 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

783 ) -> common.SignJwtResponse: 

784 r"""Signs a JWT using a service account's system-managed 

785 private key. 

786 

787 .. code-block:: python 

788 

789 # This snippet has been automatically generated and should be regarded as a 

790 # code template only. 

791 # It will require modifications to work: 

792 # - It may require correct/in-range values for request initialization. 

793 # - It may require specifying regional endpoints when creating the service 

794 # client as shown in: 

795 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

796 from google.cloud import iam_credentials_v1 

797 

798 async def sample_sign_jwt(): 

799 # Create a client 

800 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

801 

802 # Initialize request argument(s) 

803 request = iam_credentials_v1.SignJwtRequest( 

804 name="name_value", 

805 payload="payload_value", 

806 ) 

807 

808 # Make the request 

809 response = await client.sign_jwt(request=request) 

810 

811 # Handle the response 

812 print(response) 

813 

814 Args: 

815 request (Optional[Union[google.cloud.iam_credentials_v1.types.SignJwtRequest, dict]]): 

816 The request object. 

817 name (:class:`str`): 

818 Required. The resource name of the service account for 

819 which the credentials are requested, in the following 

820 format: 

821 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

822 The ``-`` wildcard character is required; replacing it 

823 with a project ID is invalid. 

824 

825 This corresponds to the ``name`` field 

826 on the ``request`` instance; if ``request`` is provided, this 

827 should not be set. 

828 delegates (:class:`MutableSequence[str]`): 

829 The sequence of service accounts in a delegation chain. 

830 Each service account must be granted the 

831 ``roles/iam.serviceAccountTokenCreator`` role on its 

832 next service account in the chain. The last service 

833 account in the chain must be granted the 

834 ``roles/iam.serviceAccountTokenCreator`` role on the 

835 service account that is specified in the ``name`` field 

836 of the request. 

837 

838 The delegates must have the following format: 

839 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. 

840 The ``-`` wildcard character is required; replacing it 

841 with a project ID is invalid. 

842 

843 This corresponds to the ``delegates`` field 

844 on the ``request`` instance; if ``request`` is provided, this 

845 should not be set. 

846 payload (:class:`str`): 

847 Required. The JWT payload to sign: a 

848 JSON object that contains a JWT Claims 

849 Set. 

850 

851 This corresponds to the ``payload`` field 

852 on the ``request`` instance; if ``request`` is provided, this 

853 should not be set. 

854 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

855 should be retried. 

856 timeout (float): The timeout for this request. 

857 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

858 sent along with the request as metadata. Normally, each value must be of type `str`, 

859 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

860 be of type `bytes`. 

861 

862 Returns: 

863 google.cloud.iam_credentials_v1.types.SignJwtResponse: 

864 

865 """ 

866 # Create or coerce a protobuf request object. 

867 # - Quick check: If we got a request object, we should *not* have 

868 # gotten any keyword arguments that map to the request. 

869 flattened_params = [name, delegates, payload] 

870 has_flattened_params = ( 

871 len([param for param in flattened_params if param is not None]) > 0 

872 ) 

873 if request is not None and has_flattened_params: 

874 raise ValueError( 

875 "If the `request` argument is set, then none of " 

876 "the individual field arguments should be set." 

877 ) 

878 

879 # - Use the request object if provided (there's no risk of modifying the input as 

880 # there are no flattened fields), or create one. 

881 if not isinstance(request, common.SignJwtRequest): 

882 request = common.SignJwtRequest(request) 

883 

884 # If we have keyword arguments corresponding to fields on the 

885 # request, apply these. 

886 if name is not None: 

887 request.name = name 

888 if payload is not None: 

889 request.payload = payload 

890 if delegates: 

891 request.delegates.extend(delegates) 

892 

893 # Wrap the RPC method; this adds retry and timeout information, 

894 # and friendly error handling. 

895 rpc = self._client._transport._wrapped_methods[self._client._transport.sign_jwt] 

896 

897 # Certain fields should be provided within the metadata header; 

898 # add these here. 

899 metadata = tuple(metadata) + ( 

900 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

901 ) 

902 

903 # Validate the universe domain. 

904 self._client._validate_universe_domain() 

905 

906 # Send the request. 

907 response = await rpc( 

908 request, 

909 retry=retry, 

910 timeout=timeout, 

911 metadata=metadata, 

912 ) 

913 

914 # Done; return the response. 

915 return response 

916 

917 async def __aenter__(self) -> "IAMCredentialsAsyncClient": 

918 return self 

919 

920 async def __aexit__(self, exc_type, exc, tb): 

921 await self.transport.close() 

922 

923 

924DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

925 gapic_version=package_version.__version__ 

926) 

927 

928if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

929 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

930 

931 

932__all__ = ("IAMCredentialsAsyncClient",)