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

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

146 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# 

16from collections import OrderedDict 

17import logging as std_logging 

18import re 

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 

32from google.api_core import exceptions as core_exceptions 

33from google.api_core import gapic_v1 

34from google.api_core import retry_async as retries 

35from google.api_core.client_options import ClientOptions 

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

37from google.oauth2 import service_account # type: ignore 

38import google.protobuf 

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 

47from google.protobuf import duration_pb2 # type: ignore 

48from google.protobuf import 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 return IAMCredentialsClient.from_service_account_info.__func__(IAMCredentialsAsyncClient, info, *args, **kwargs) # type: ignore 

131 

132 @classmethod 

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

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

135 file. 

136 

137 Args: 

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

139 file. 

140 args: Additional arguments to pass to the constructor. 

141 kwargs: Additional arguments to pass to the constructor. 

142 

143 Returns: 

144 IAMCredentialsAsyncClient: The constructed client. 

145 """ 

146 return IAMCredentialsClient.from_service_account_file.__func__(IAMCredentialsAsyncClient, filename, *args, **kwargs) # type: ignore 

147 

148 from_service_account_json = from_service_account_file 

149 

150 @classmethod 

151 def get_mtls_endpoint_and_cert_source( 

152 cls, client_options: Optional[ClientOptions] = None 

153 ): 

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

155 

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

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

158 client cert source is None. 

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

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

161 source is None. 

162 

163 The API endpoint is determined in the following order: 

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

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

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

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

168 use the default API endpoint. 

169 

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

171 

172 Args: 

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

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

175 in this method. 

176 

177 Returns: 

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

179 client cert source to use. 

180 

181 Raises: 

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

183 """ 

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

185 

186 @property 

187 def transport(self) -> IAMCredentialsTransport: 

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

189 

190 Returns: 

191 IAMCredentialsTransport: The transport used by the client instance. 

192 """ 

193 return self._client.transport 

194 

195 @property 

196 def api_endpoint(self): 

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

198 

199 Returns: 

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

201 """ 

202 return self._client._api_endpoint 

203 

204 @property 

205 def universe_domain(self) -> str: 

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

207 

208 Returns: 

209 str: The universe domain used 

210 by the client instance. 

211 """ 

212 return self._client._universe_domain 

213 

214 get_transport_class = IAMCredentialsClient.get_transport_class 

215 

216 def __init__( 

217 self, 

218 *, 

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

220 transport: Optional[ 

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

222 ] = "grpc_asyncio", 

223 client_options: Optional[ClientOptions] = None, 

224 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

225 ) -> None: 

226 """Instantiates the iam credentials async client. 

227 

228 Args: 

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

230 authorization credentials to attach to requests. These 

231 credentials identify the application to the service; if none 

232 are specified, the client will attempt to ascertain the 

233 credentials from the environment. 

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

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

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

237 arguments as used in the IAMCredentialsTransport constructor. 

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

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

240 Custom options for the client. 

241 

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

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

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

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

246 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

247 variable, which have one of the following values: 

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

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

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

251 the default value). 

252 

253 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

255 to provide a client certificate for mTLS transport. If 

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

257 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

258 set, no client certificate will be used. 

259 

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

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

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

263 currently not supported for mTLS. 

264 

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

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

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

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

269 your own client library. 

270 

271 Raises: 

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

273 creation failed for any reason. 

274 """ 

275 self._client = IAMCredentialsClient( 

276 credentials=credentials, 

277 transport=transport, 

278 client_options=client_options, 

279 client_info=client_info, 

280 ) 

281 

282 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

283 std_logging.DEBUG 

284 ): # pragma: NO COVER 

285 _LOGGER.debug( 

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

287 extra={ 

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

289 "universeDomain": getattr( 

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

291 ), 

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

293 "credentialsInfo": getattr( 

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

295 )(), 

296 } 

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

298 else { 

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

300 "credentialsType": None, 

301 }, 

302 ) 

303 

304 async def generate_access_token( 

305 self, 

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

307 *, 

308 name: Optional[str] = None, 

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

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

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

312 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

315 ) -> common.GenerateAccessTokenResponse: 

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

317 account. 

318 

319 .. code-block:: python 

320 

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

322 # code template only. 

323 # It will require modifications to work: 

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

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

326 # client as shown in: 

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

328 from google.cloud import iam_credentials_v1 

329 

330 async def sample_generate_access_token(): 

331 # Create a client 

332 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

333 

334 # Initialize request argument(s) 

335 request = iam_credentials_v1.GenerateAccessTokenRequest( 

336 name="name_value", 

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

338 ) 

339 

340 # Make the request 

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

342 

343 # Handle the response 

344 print(response) 

345 

346 Args: 

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

348 The request object. 

349 name (:class:`str`): 

350 Required. The resource name of the service account for 

351 which the credentials are requested, in the following 

352 format: 

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

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

355 with a project ID is invalid. 

356 

357 This corresponds to the ``name`` field 

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

359 should not be set. 

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

361 The sequence of service accounts in a delegation chain. 

362 Each service account must be granted the 

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

364 next service account in the chain. The last service 

365 account in the chain must be granted the 

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

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

368 of the request. 

369 

370 The delegates must have the following format: 

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

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

373 with a project ID is invalid. 

374 

375 This corresponds to the ``delegates`` field 

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

377 should not be set. 

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

379 Required. Code to identify the scopes 

380 to be included in the OAuth 2.0 access 

381 token. See 

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

383 for more information. 

384 At least one value required. 

385 

386 This corresponds to the ``scope`` field 

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

388 should not be set. 

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

390 The desired lifetime duration of the 

391 access token in seconds. Must be set to 

392 a value less than or equal to 3600 (1 

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

394 token's lifetime will be set to a 

395 default value of one hour. 

396 

397 This corresponds to the ``lifetime`` field 

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

399 should not be set. 

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

401 should be retried. 

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

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

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

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

406 be of type `bytes`. 

407 

408 Returns: 

409 google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse: 

410 

411 """ 

412 # Create or coerce a protobuf request object. 

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

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

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

416 has_flattened_params = ( 

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

418 ) 

419 if request is not None and has_flattened_params: 

420 raise ValueError( 

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

422 "the individual field arguments should be set." 

423 ) 

424 

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

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

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

428 request = common.GenerateAccessTokenRequest(request) 

429 

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

431 # request, apply these. 

432 if name is not None: 

433 request.name = name 

434 if lifetime is not None: 

435 request.lifetime = lifetime 

436 if delegates: 

437 request.delegates.extend(delegates) 

438 if scope: 

439 request.scope.extend(scope) 

440 

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

442 # and friendly error handling. 

443 rpc = self._client._transport._wrapped_methods[ 

444 self._client._transport.generate_access_token 

445 ] 

446 

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

448 # add these here. 

449 metadata = tuple(metadata) + ( 

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

451 ) 

452 

453 # Validate the universe domain. 

454 self._client._validate_universe_domain() 

455 

456 # Send the request. 

457 response = await rpc( 

458 request, 

459 retry=retry, 

460 timeout=timeout, 

461 metadata=metadata, 

462 ) 

463 

464 # Done; return the response. 

465 return response 

466 

467 async def generate_id_token( 

468 self, 

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

470 *, 

471 name: Optional[str] = None, 

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

473 audience: Optional[str] = None, 

474 include_email: Optional[bool] = None, 

475 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

478 ) -> common.GenerateIdTokenResponse: 

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

480 account. 

481 

482 .. code-block:: python 

483 

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

485 # code template only. 

486 # It will require modifications to work: 

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

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

489 # client as shown in: 

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

491 from google.cloud import iam_credentials_v1 

492 

493 async def sample_generate_id_token(): 

494 # Create a client 

495 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

496 

497 # Initialize request argument(s) 

498 request = iam_credentials_v1.GenerateIdTokenRequest( 

499 name="name_value", 

500 audience="audience_value", 

501 ) 

502 

503 # Make the request 

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

505 

506 # Handle the response 

507 print(response) 

508 

509 Args: 

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

511 The request object. 

512 name (:class:`str`): 

513 Required. The resource name of the service account for 

514 which the credentials are requested, in the following 

515 format: 

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

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

518 with a project ID is invalid. 

519 

520 This corresponds to the ``name`` field 

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

522 should not be set. 

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

524 The sequence of service accounts in a delegation chain. 

525 Each service account must be granted the 

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

527 next service account in the chain. The last service 

528 account in the chain must be granted the 

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

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

531 of the request. 

532 

533 The delegates must have the following format: 

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

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

536 with a project ID is invalid. 

537 

538 This corresponds to the ``delegates`` field 

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

540 should not be set. 

541 audience (:class:`str`): 

542 Required. The audience for the token, 

543 such as the API or account that this 

544 token grants access to. 

545 

546 This corresponds to the ``audience`` field 

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

548 should not be set. 

549 include_email (:class:`bool`): 

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

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

552 ``email_verified`` claims. 

553 

554 This corresponds to the ``include_email`` field 

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

556 should not be set. 

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

558 should be retried. 

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

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

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

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

563 be of type `bytes`. 

564 

565 Returns: 

566 google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse: 

567 

568 """ 

569 # Create or coerce a protobuf request object. 

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

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

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

573 has_flattened_params = ( 

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

575 ) 

576 if request is not None and has_flattened_params: 

577 raise ValueError( 

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

579 "the individual field arguments should be set." 

580 ) 

581 

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

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

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

585 request = common.GenerateIdTokenRequest(request) 

586 

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

588 # request, apply these. 

589 if name is not None: 

590 request.name = name 

591 if audience is not None: 

592 request.audience = audience 

593 if include_email is not None: 

594 request.include_email = include_email 

595 if delegates: 

596 request.delegates.extend(delegates) 

597 

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

599 # and friendly error handling. 

600 rpc = self._client._transport._wrapped_methods[ 

601 self._client._transport.generate_id_token 

602 ] 

603 

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

605 # add these here. 

606 metadata = tuple(metadata) + ( 

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

608 ) 

609 

610 # Validate the universe domain. 

611 self._client._validate_universe_domain() 

612 

613 # Send the request. 

614 response = await rpc( 

615 request, 

616 retry=retry, 

617 timeout=timeout, 

618 metadata=metadata, 

619 ) 

620 

621 # Done; return the response. 

622 return response 

623 

624 async def sign_blob( 

625 self, 

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

627 *, 

628 name: Optional[str] = None, 

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

630 payload: Optional[bytes] = None, 

631 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

634 ) -> common.SignBlobResponse: 

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

636 private key. 

637 

638 .. code-block:: python 

639 

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

641 # code template only. 

642 # It will require modifications to work: 

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

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

645 # client as shown in: 

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

647 from google.cloud import iam_credentials_v1 

648 

649 async def sample_sign_blob(): 

650 # Create a client 

651 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

652 

653 # Initialize request argument(s) 

654 request = iam_credentials_v1.SignBlobRequest( 

655 name="name_value", 

656 payload=b'payload_blob', 

657 ) 

658 

659 # Make the request 

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

661 

662 # Handle the response 

663 print(response) 

664 

665 Args: 

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

667 The request object. 

668 name (:class:`str`): 

669 Required. The resource name of the service account for 

670 which the credentials are requested, in the following 

671 format: 

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

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

674 with a project ID is invalid. 

675 

676 This corresponds to the ``name`` field 

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

678 should not be set. 

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

680 The sequence of service accounts in a delegation chain. 

681 Each service account must be granted the 

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

683 next service account in the chain. The last service 

684 account in the chain must be granted the 

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

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

687 of the request. 

688 

689 The delegates must have the following format: 

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

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

692 with a project ID is invalid. 

693 

694 This corresponds to the ``delegates`` field 

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

696 should not be set. 

697 payload (:class:`bytes`): 

698 Required. The bytes to sign. 

699 This corresponds to the ``payload`` field 

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

701 should not be set. 

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

703 should be retried. 

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

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

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

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

708 be of type `bytes`. 

709 

710 Returns: 

711 google.cloud.iam_credentials_v1.types.SignBlobResponse: 

712 

713 """ 

714 # Create or coerce a protobuf request object. 

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

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

717 flattened_params = [name, delegates, payload] 

718 has_flattened_params = ( 

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

720 ) 

721 if request is not None and has_flattened_params: 

722 raise ValueError( 

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

724 "the individual field arguments should be set." 

725 ) 

726 

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

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

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

730 request = common.SignBlobRequest(request) 

731 

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

733 # request, apply these. 

734 if name is not None: 

735 request.name = name 

736 if payload is not None: 

737 request.payload = payload 

738 if delegates: 

739 request.delegates.extend(delegates) 

740 

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

742 # and friendly error handling. 

743 rpc = self._client._transport._wrapped_methods[ 

744 self._client._transport.sign_blob 

745 ] 

746 

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

748 # add these here. 

749 metadata = tuple(metadata) + ( 

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

751 ) 

752 

753 # Validate the universe domain. 

754 self._client._validate_universe_domain() 

755 

756 # Send the request. 

757 response = await rpc( 

758 request, 

759 retry=retry, 

760 timeout=timeout, 

761 metadata=metadata, 

762 ) 

763 

764 # Done; return the response. 

765 return response 

766 

767 async def sign_jwt( 

768 self, 

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

770 *, 

771 name: Optional[str] = None, 

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

773 payload: Optional[str] = None, 

774 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

777 ) -> common.SignJwtResponse: 

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

779 private key. 

780 

781 .. code-block:: python 

782 

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

784 # code template only. 

785 # It will require modifications to work: 

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

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

788 # client as shown in: 

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

790 from google.cloud import iam_credentials_v1 

791 

792 async def sample_sign_jwt(): 

793 # Create a client 

794 client = iam_credentials_v1.IAMCredentialsAsyncClient() 

795 

796 # Initialize request argument(s) 

797 request = iam_credentials_v1.SignJwtRequest( 

798 name="name_value", 

799 payload="payload_value", 

800 ) 

801 

802 # Make the request 

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

804 

805 # Handle the response 

806 print(response) 

807 

808 Args: 

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

810 The request object. 

811 name (:class:`str`): 

812 Required. The resource name of the service account for 

813 which the credentials are requested, in the following 

814 format: 

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

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

817 with a project ID is invalid. 

818 

819 This corresponds to the ``name`` field 

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

821 should not be set. 

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

823 The sequence of service accounts in a delegation chain. 

824 Each service account must be granted the 

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

826 next service account in the chain. The last service 

827 account in the chain must be granted the 

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

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

830 of the request. 

831 

832 The delegates must have the following format: 

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

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

835 with a project ID is invalid. 

836 

837 This corresponds to the ``delegates`` field 

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

839 should not be set. 

840 payload (:class:`str`): 

841 Required. The JWT payload to sign: a 

842 JSON object that contains a JWT Claims 

843 Set. 

844 

845 This corresponds to the ``payload`` field 

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

847 should not be set. 

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

849 should be retried. 

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

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

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

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

854 be of type `bytes`. 

855 

856 Returns: 

857 google.cloud.iam_credentials_v1.types.SignJwtResponse: 

858 

859 """ 

860 # Create or coerce a protobuf request object. 

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

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

863 flattened_params = [name, delegates, payload] 

864 has_flattened_params = ( 

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

866 ) 

867 if request is not None and has_flattened_params: 

868 raise ValueError( 

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

870 "the individual field arguments should be set." 

871 ) 

872 

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

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

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

876 request = common.SignJwtRequest(request) 

877 

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

879 # request, apply these. 

880 if name is not None: 

881 request.name = name 

882 if payload is not None: 

883 request.payload = payload 

884 if delegates: 

885 request.delegates.extend(delegates) 

886 

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

888 # and friendly error handling. 

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

890 

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

892 # add these here. 

893 metadata = tuple(metadata) + ( 

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

895 ) 

896 

897 # Validate the universe domain. 

898 self._client._validate_universe_domain() 

899 

900 # Send the request. 

901 response = await rpc( 

902 request, 

903 retry=retry, 

904 timeout=timeout, 

905 metadata=metadata, 

906 ) 

907 

908 # Done; return the response. 

909 return response 

910 

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

912 return self 

913 

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

915 await self.transport.close() 

916 

917 

918DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

919 gapic_version=package_version.__version__ 

920) 

921 

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

923 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

924 

925 

926__all__ = ("IAMCredentialsAsyncClient",)