1# -*- coding: utf-8 -*-
2# Copyright 2023 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 functools
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29)
30
31from google.api_core import exceptions as core_exceptions
32from google.api_core import gapic_v1
33from google.api_core import retry as retries
34from google.api_core.client_options import ClientOptions
35from google.auth import credentials as ga_credentials # type: ignore
36from google.oauth2 import service_account # type: ignore
37
38from google.cloud.iam_credentials_v1 import gapic_version as package_version
39
40try:
41 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
42except AttributeError: # pragma: NO COVER
43 OptionalRetry = Union[retries.Retry, object] # type: ignore
44
45from google.protobuf import duration_pb2 # type: ignore
46from google.protobuf import timestamp_pb2 # type: ignore
47
48from google.cloud.iam_credentials_v1.types import common
49
50from .client import IAMCredentialsClient
51from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport
52from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport
53
54
55class IAMCredentialsAsyncClient:
56 """A service account is a special type of Google account that
57 belongs to your application or a virtual machine (VM), instead
58 of to an individual end user. Your application assumes the
59 identity of the service account to call Google APIs, so that the
60 users aren't directly involved.
61
62 Service account credentials are used to temporarily assume the
63 identity of the service account. Supported credential types
64 include OAuth 2.0 access tokens, OpenID Connect ID tokens,
65 self-signed JSON Web Tokens (JWTs), and more.
66 """
67
68 _client: IAMCredentialsClient
69
70 DEFAULT_ENDPOINT = IAMCredentialsClient.DEFAULT_ENDPOINT
71 DEFAULT_MTLS_ENDPOINT = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT
72
73 service_account_path = staticmethod(IAMCredentialsClient.service_account_path)
74 parse_service_account_path = staticmethod(
75 IAMCredentialsClient.parse_service_account_path
76 )
77 common_billing_account_path = staticmethod(
78 IAMCredentialsClient.common_billing_account_path
79 )
80 parse_common_billing_account_path = staticmethod(
81 IAMCredentialsClient.parse_common_billing_account_path
82 )
83 common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path)
84 parse_common_folder_path = staticmethod(
85 IAMCredentialsClient.parse_common_folder_path
86 )
87 common_organization_path = staticmethod(
88 IAMCredentialsClient.common_organization_path
89 )
90 parse_common_organization_path = staticmethod(
91 IAMCredentialsClient.parse_common_organization_path
92 )
93 common_project_path = staticmethod(IAMCredentialsClient.common_project_path)
94 parse_common_project_path = staticmethod(
95 IAMCredentialsClient.parse_common_project_path
96 )
97 common_location_path = staticmethod(IAMCredentialsClient.common_location_path)
98 parse_common_location_path = staticmethod(
99 IAMCredentialsClient.parse_common_location_path
100 )
101
102 @classmethod
103 def from_service_account_info(cls, info: dict, *args, **kwargs):
104 """Creates an instance of this client using the provided credentials
105 info.
106
107 Args:
108 info (dict): The service account private key info.
109 args: Additional arguments to pass to the constructor.
110 kwargs: Additional arguments to pass to the constructor.
111
112 Returns:
113 IAMCredentialsAsyncClient: The constructed client.
114 """
115 return IAMCredentialsClient.from_service_account_info.__func__(IAMCredentialsAsyncClient, info, *args, **kwargs) # type: ignore
116
117 @classmethod
118 def from_service_account_file(cls, filename: str, *args, **kwargs):
119 """Creates an instance of this client using the provided credentials
120 file.
121
122 Args:
123 filename (str): The path to the service account private key json
124 file.
125 args: Additional arguments to pass to the constructor.
126 kwargs: Additional arguments to pass to the constructor.
127
128 Returns:
129 IAMCredentialsAsyncClient: The constructed client.
130 """
131 return IAMCredentialsClient.from_service_account_file.__func__(IAMCredentialsAsyncClient, filename, *args, **kwargs) # type: ignore
132
133 from_service_account_json = from_service_account_file
134
135 @classmethod
136 def get_mtls_endpoint_and_cert_source(
137 cls, client_options: Optional[ClientOptions] = None
138 ):
139 """Return the API endpoint and client cert source for mutual TLS.
140
141 The client cert source is determined in the following order:
142 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
143 client cert source is None.
144 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
145 default client cert source exists, use the default one; otherwise the client cert
146 source is None.
147
148 The API endpoint is determined in the following order:
149 (1) if `client_options.api_endpoint` if provided, use the provided one.
150 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
151 default mTLS endpoint; if the environment variable is "never", use the default API
152 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
153 use the default API endpoint.
154
155 More details can be found at https://google.aip.dev/auth/4114.
156
157 Args:
158 client_options (google.api_core.client_options.ClientOptions): Custom options for the
159 client. Only the `api_endpoint` and `client_cert_source` properties may be used
160 in this method.
161
162 Returns:
163 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
164 client cert source to use.
165
166 Raises:
167 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
168 """
169 return IAMCredentialsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
170
171 @property
172 def transport(self) -> IAMCredentialsTransport:
173 """Returns the transport used by the client instance.
174
175 Returns:
176 IAMCredentialsTransport: The transport used by the client instance.
177 """
178 return self._client.transport
179
180 get_transport_class = functools.partial(
181 type(IAMCredentialsClient).get_transport_class, type(IAMCredentialsClient)
182 )
183
184 def __init__(
185 self,
186 *,
187 credentials: Optional[ga_credentials.Credentials] = None,
188 transport: Union[str, IAMCredentialsTransport] = "grpc_asyncio",
189 client_options: Optional[ClientOptions] = None,
190 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
191 ) -> None:
192 """Instantiates the iam credentials client.
193
194 Args:
195 credentials (Optional[google.auth.credentials.Credentials]): The
196 authorization credentials to attach to requests. These
197 credentials identify the application to the service; if none
198 are specified, the client will attempt to ascertain the
199 credentials from the environment.
200 transport (Union[str, ~.IAMCredentialsTransport]): The
201 transport to use. If set to None, a transport is chosen
202 automatically.
203 client_options (ClientOptions): Custom options for the client. It
204 won't take effect if a ``transport`` instance is provided.
205 (1) The ``api_endpoint`` property can be used to override the
206 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
207 environment variable can also be used to override the endpoint:
208 "always" (always use the default mTLS endpoint), "never" (always
209 use the default regular endpoint) and "auto" (auto switch to the
210 default mTLS endpoint if client certificate is present, this is
211 the default value). However, the ``api_endpoint`` property takes
212 precedence if provided.
213 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
214 is "true", then the ``client_cert_source`` property can be used
215 to provide client certificate for mutual TLS transport. If
216 not provided, the default SSL client certificate will be used if
217 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
218 set, no client certificate will be used.
219
220 Raises:
221 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
222 creation failed for any reason.
223 """
224 self._client = IAMCredentialsClient(
225 credentials=credentials,
226 transport=transport,
227 client_options=client_options,
228 client_info=client_info,
229 )
230
231 async def generate_access_token(
232 self,
233 request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None,
234 *,
235 name: Optional[str] = None,
236 delegates: Optional[MutableSequence[str]] = None,
237 scope: Optional[MutableSequence[str]] = None,
238 lifetime: Optional[duration_pb2.Duration] = None,
239 retry: OptionalRetry = gapic_v1.method.DEFAULT,
240 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
241 metadata: Sequence[Tuple[str, str]] = (),
242 ) -> common.GenerateAccessTokenResponse:
243 r"""Generates an OAuth 2.0 access token for a service
244 account.
245
246 .. code-block:: python
247
248 # This snippet has been automatically generated and should be regarded as a
249 # code template only.
250 # It will require modifications to work:
251 # - It may require correct/in-range values for request initialization.
252 # - It may require specifying regional endpoints when creating the service
253 # client as shown in:
254 # https://googleapis.dev/python/google-api-core/latest/client_options.html
255 from google.cloud import iam_credentials_v1
256
257 async def sample_generate_access_token():
258 # Create a client
259 client = iam_credentials_v1.IAMCredentialsAsyncClient()
260
261 # Initialize request argument(s)
262 request = iam_credentials_v1.GenerateAccessTokenRequest(
263 name="name_value",
264 scope=['scope_value1', 'scope_value2'],
265 )
266
267 # Make the request
268 response = await client.generate_access_token(request=request)
269
270 # Handle the response
271 print(response)
272
273 Args:
274 request (Optional[Union[google.cloud.iam_credentials_v1.types.GenerateAccessTokenRequest, dict]]):
275 The request object.
276 name (:class:`str`):
277 Required. The resource name of the service account for
278 which the credentials are requested, in the following
279 format:
280 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
281 The ``-`` wildcard character is required; replacing it
282 with a project ID is invalid.
283
284 This corresponds to the ``name`` field
285 on the ``request`` instance; if ``request`` is provided, this
286 should not be set.
287 delegates (:class:`MutableSequence[str]`):
288 The sequence of service accounts in a delegation chain.
289 Each service account must be granted the
290 ``roles/iam.serviceAccountTokenCreator`` role on its
291 next service account in the chain. The last service
292 account in the chain must be granted the
293 ``roles/iam.serviceAccountTokenCreator`` role on the
294 service account that is specified in the ``name`` field
295 of the request.
296
297 The delegates must have the following format:
298 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
299 The ``-`` wildcard character is required; replacing it
300 with a project ID is invalid.
301
302 This corresponds to the ``delegates`` field
303 on the ``request`` instance; if ``request`` is provided, this
304 should not be set.
305 scope (:class:`MutableSequence[str]`):
306 Required. Code to identify the scopes
307 to be included in the OAuth 2.0 access
308 token. See
309 https://developers.google.com/identity/protocols/googlescopes
310 for more information.
311 At least one value required.
312
313 This corresponds to the ``scope`` field
314 on the ``request`` instance; if ``request`` is provided, this
315 should not be set.
316 lifetime (:class:`google.protobuf.duration_pb2.Duration`):
317 The desired lifetime duration of the
318 access token in seconds. Must be set to
319 a value less than or equal to 3600 (1
320 hour). If a value is not specified, the
321 token's lifetime will be set to a
322 default value of one hour.
323
324 This corresponds to the ``lifetime`` field
325 on the ``request`` instance; if ``request`` is provided, this
326 should not be set.
327 retry (google.api_core.retry.Retry): Designation of what errors, if any,
328 should be retried.
329 timeout (float): The timeout for this request.
330 metadata (Sequence[Tuple[str, str]]): Strings which should be
331 sent along with the request as metadata.
332
333 Returns:
334 google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse:
335
336 """
337 # Create or coerce a protobuf request object.
338 # Quick check: If we got a request object, we should *not* have
339 # gotten any keyword arguments that map to the request.
340 has_flattened_params = any([name, delegates, scope, lifetime])
341 if request is not None and has_flattened_params:
342 raise ValueError(
343 "If the `request` argument is set, then none of "
344 "the individual field arguments should be set."
345 )
346
347 request = common.GenerateAccessTokenRequest(request)
348
349 # If we have keyword arguments corresponding to fields on the
350 # request, apply these.
351 if name is not None:
352 request.name = name
353 if lifetime is not None:
354 request.lifetime = lifetime
355 if delegates:
356 request.delegates.extend(delegates)
357 if scope:
358 request.scope.extend(scope)
359
360 # Wrap the RPC method; this adds retry and timeout information,
361 # and friendly error handling.
362 rpc = gapic_v1.method_async.wrap_method(
363 self._client._transport.generate_access_token,
364 default_retry=retries.Retry(
365 initial=0.1,
366 maximum=60.0,
367 multiplier=1.3,
368 predicate=retries.if_exception_type(
369 core_exceptions.DeadlineExceeded,
370 core_exceptions.ServiceUnavailable,
371 ),
372 deadline=60.0,
373 ),
374 default_timeout=60.0,
375 client_info=DEFAULT_CLIENT_INFO,
376 )
377
378 # Certain fields should be provided within the metadata header;
379 # add these here.
380 metadata = tuple(metadata) + (
381 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
382 )
383
384 # Send the request.
385 response = await rpc(
386 request,
387 retry=retry,
388 timeout=timeout,
389 metadata=metadata,
390 )
391
392 # Done; return the response.
393 return response
394
395 async def generate_id_token(
396 self,
397 request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None,
398 *,
399 name: Optional[str] = None,
400 delegates: Optional[MutableSequence[str]] = None,
401 audience: Optional[str] = None,
402 include_email: Optional[bool] = None,
403 retry: OptionalRetry = gapic_v1.method.DEFAULT,
404 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
405 metadata: Sequence[Tuple[str, str]] = (),
406 ) -> common.GenerateIdTokenResponse:
407 r"""Generates an OpenID Connect ID token for a service
408 account.
409
410 .. code-block:: python
411
412 # This snippet has been automatically generated and should be regarded as a
413 # code template only.
414 # It will require modifications to work:
415 # - It may require correct/in-range values for request initialization.
416 # - It may require specifying regional endpoints when creating the service
417 # client as shown in:
418 # https://googleapis.dev/python/google-api-core/latest/client_options.html
419 from google.cloud import iam_credentials_v1
420
421 async def sample_generate_id_token():
422 # Create a client
423 client = iam_credentials_v1.IAMCredentialsAsyncClient()
424
425 # Initialize request argument(s)
426 request = iam_credentials_v1.GenerateIdTokenRequest(
427 name="name_value",
428 audience="audience_value",
429 )
430
431 # Make the request
432 response = await client.generate_id_token(request=request)
433
434 # Handle the response
435 print(response)
436
437 Args:
438 request (Optional[Union[google.cloud.iam_credentials_v1.types.GenerateIdTokenRequest, dict]]):
439 The request object.
440 name (:class:`str`):
441 Required. The resource name of the service account for
442 which the credentials are requested, in the following
443 format:
444 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
445 The ``-`` wildcard character is required; replacing it
446 with a project ID is invalid.
447
448 This corresponds to the ``name`` field
449 on the ``request`` instance; if ``request`` is provided, this
450 should not be set.
451 delegates (:class:`MutableSequence[str]`):
452 The sequence of service accounts in a delegation chain.
453 Each service account must be granted the
454 ``roles/iam.serviceAccountTokenCreator`` role on its
455 next service account in the chain. The last service
456 account in the chain must be granted the
457 ``roles/iam.serviceAccountTokenCreator`` role on the
458 service account that is specified in the ``name`` field
459 of the request.
460
461 The delegates must have the following format:
462 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
463 The ``-`` wildcard character is required; replacing it
464 with a project ID is invalid.
465
466 This corresponds to the ``delegates`` field
467 on the ``request`` instance; if ``request`` is provided, this
468 should not be set.
469 audience (:class:`str`):
470 Required. The audience for the token,
471 such as the API or account that this
472 token grants access to.
473
474 This corresponds to the ``audience`` field
475 on the ``request`` instance; if ``request`` is provided, this
476 should not be set.
477 include_email (:class:`bool`):
478 Include the service account email in the token. If set
479 to ``true``, the token will contain ``email`` and
480 ``email_verified`` claims.
481
482 This corresponds to the ``include_email`` field
483 on the ``request`` instance; if ``request`` is provided, this
484 should not be set.
485 retry (google.api_core.retry.Retry): Designation of what errors, if any,
486 should be retried.
487 timeout (float): The timeout for this request.
488 metadata (Sequence[Tuple[str, str]]): Strings which should be
489 sent along with the request as metadata.
490
491 Returns:
492 google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse:
493
494 """
495 # Create or coerce a protobuf request object.
496 # Quick check: If we got a request object, we should *not* have
497 # gotten any keyword arguments that map to the request.
498 has_flattened_params = any([name, delegates, audience, include_email])
499 if request is not None and has_flattened_params:
500 raise ValueError(
501 "If the `request` argument is set, then none of "
502 "the individual field arguments should be set."
503 )
504
505 request = common.GenerateIdTokenRequest(request)
506
507 # If we have keyword arguments corresponding to fields on the
508 # request, apply these.
509 if name is not None:
510 request.name = name
511 if audience is not None:
512 request.audience = audience
513 if include_email is not None:
514 request.include_email = include_email
515 if delegates:
516 request.delegates.extend(delegates)
517
518 # Wrap the RPC method; this adds retry and timeout information,
519 # and friendly error handling.
520 rpc = gapic_v1.method_async.wrap_method(
521 self._client._transport.generate_id_token,
522 default_retry=retries.Retry(
523 initial=0.1,
524 maximum=60.0,
525 multiplier=1.3,
526 predicate=retries.if_exception_type(
527 core_exceptions.DeadlineExceeded,
528 core_exceptions.ServiceUnavailable,
529 ),
530 deadline=60.0,
531 ),
532 default_timeout=60.0,
533 client_info=DEFAULT_CLIENT_INFO,
534 )
535
536 # Certain fields should be provided within the metadata header;
537 # add these here.
538 metadata = tuple(metadata) + (
539 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
540 )
541
542 # Send the request.
543 response = await rpc(
544 request,
545 retry=retry,
546 timeout=timeout,
547 metadata=metadata,
548 )
549
550 # Done; return the response.
551 return response
552
553 async def sign_blob(
554 self,
555 request: Optional[Union[common.SignBlobRequest, dict]] = None,
556 *,
557 name: Optional[str] = None,
558 delegates: Optional[MutableSequence[str]] = None,
559 payload: Optional[bytes] = None,
560 retry: OptionalRetry = gapic_v1.method.DEFAULT,
561 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
562 metadata: Sequence[Tuple[str, str]] = (),
563 ) -> common.SignBlobResponse:
564 r"""Signs a blob using a service account's system-managed
565 private key.
566
567 .. code-block:: python
568
569 # This snippet has been automatically generated and should be regarded as a
570 # code template only.
571 # It will require modifications to work:
572 # - It may require correct/in-range values for request initialization.
573 # - It may require specifying regional endpoints when creating the service
574 # client as shown in:
575 # https://googleapis.dev/python/google-api-core/latest/client_options.html
576 from google.cloud import iam_credentials_v1
577
578 async def sample_sign_blob():
579 # Create a client
580 client = iam_credentials_v1.IAMCredentialsAsyncClient()
581
582 # Initialize request argument(s)
583 request = iam_credentials_v1.SignBlobRequest(
584 name="name_value",
585 payload=b'payload_blob',
586 )
587
588 # Make the request
589 response = await client.sign_blob(request=request)
590
591 # Handle the response
592 print(response)
593
594 Args:
595 request (Optional[Union[google.cloud.iam_credentials_v1.types.SignBlobRequest, dict]]):
596 The request object.
597 name (:class:`str`):
598 Required. The resource name of the service account for
599 which the credentials are requested, in the following
600 format:
601 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
602 The ``-`` wildcard character is required; replacing it
603 with a project ID is invalid.
604
605 This corresponds to the ``name`` field
606 on the ``request`` instance; if ``request`` is provided, this
607 should not be set.
608 delegates (:class:`MutableSequence[str]`):
609 The sequence of service accounts in a delegation chain.
610 Each service account must be granted the
611 ``roles/iam.serviceAccountTokenCreator`` role on its
612 next service account in the chain. The last service
613 account in the chain must be granted the
614 ``roles/iam.serviceAccountTokenCreator`` role on the
615 service account that is specified in the ``name`` field
616 of the request.
617
618 The delegates must have the following format:
619 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
620 The ``-`` wildcard character is required; replacing it
621 with a project ID is invalid.
622
623 This corresponds to the ``delegates`` field
624 on the ``request`` instance; if ``request`` is provided, this
625 should not be set.
626 payload (:class:`bytes`):
627 Required. The bytes to sign.
628 This corresponds to the ``payload`` field
629 on the ``request`` instance; if ``request`` is provided, this
630 should not be set.
631 retry (google.api_core.retry.Retry): Designation of what errors, if any,
632 should be retried.
633 timeout (float): The timeout for this request.
634 metadata (Sequence[Tuple[str, str]]): Strings which should be
635 sent along with the request as metadata.
636
637 Returns:
638 google.cloud.iam_credentials_v1.types.SignBlobResponse:
639
640 """
641 # Create or coerce a protobuf request object.
642 # Quick check: If we got a request object, we should *not* have
643 # gotten any keyword arguments that map to the request.
644 has_flattened_params = any([name, delegates, payload])
645 if request is not None and has_flattened_params:
646 raise ValueError(
647 "If the `request` argument is set, then none of "
648 "the individual field arguments should be set."
649 )
650
651 request = common.SignBlobRequest(request)
652
653 # If we have keyword arguments corresponding to fields on the
654 # request, apply these.
655 if name is not None:
656 request.name = name
657 if payload is not None:
658 request.payload = payload
659 if delegates:
660 request.delegates.extend(delegates)
661
662 # Wrap the RPC method; this adds retry and timeout information,
663 # and friendly error handling.
664 rpc = gapic_v1.method_async.wrap_method(
665 self._client._transport.sign_blob,
666 default_retry=retries.Retry(
667 initial=0.1,
668 maximum=60.0,
669 multiplier=1.3,
670 predicate=retries.if_exception_type(
671 core_exceptions.DeadlineExceeded,
672 core_exceptions.ServiceUnavailable,
673 ),
674 deadline=60.0,
675 ),
676 default_timeout=60.0,
677 client_info=DEFAULT_CLIENT_INFO,
678 )
679
680 # Certain fields should be provided within the metadata header;
681 # add these here.
682 metadata = tuple(metadata) + (
683 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
684 )
685
686 # Send the request.
687 response = await rpc(
688 request,
689 retry=retry,
690 timeout=timeout,
691 metadata=metadata,
692 )
693
694 # Done; return the response.
695 return response
696
697 async def sign_jwt(
698 self,
699 request: Optional[Union[common.SignJwtRequest, dict]] = None,
700 *,
701 name: Optional[str] = None,
702 delegates: Optional[MutableSequence[str]] = None,
703 payload: Optional[str] = None,
704 retry: OptionalRetry = gapic_v1.method.DEFAULT,
705 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
706 metadata: Sequence[Tuple[str, str]] = (),
707 ) -> common.SignJwtResponse:
708 r"""Signs a JWT using a service account's system-managed
709 private key.
710
711 .. code-block:: python
712
713 # This snippet has been automatically generated and should be regarded as a
714 # code template only.
715 # It will require modifications to work:
716 # - It may require correct/in-range values for request initialization.
717 # - It may require specifying regional endpoints when creating the service
718 # client as shown in:
719 # https://googleapis.dev/python/google-api-core/latest/client_options.html
720 from google.cloud import iam_credentials_v1
721
722 async def sample_sign_jwt():
723 # Create a client
724 client = iam_credentials_v1.IAMCredentialsAsyncClient()
725
726 # Initialize request argument(s)
727 request = iam_credentials_v1.SignJwtRequest(
728 name="name_value",
729 payload="payload_value",
730 )
731
732 # Make the request
733 response = await client.sign_jwt(request=request)
734
735 # Handle the response
736 print(response)
737
738 Args:
739 request (Optional[Union[google.cloud.iam_credentials_v1.types.SignJwtRequest, dict]]):
740 The request object.
741 name (:class:`str`):
742 Required. The resource name of the service account for
743 which the credentials are requested, in the following
744 format:
745 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
746 The ``-`` wildcard character is required; replacing it
747 with a project ID is invalid.
748
749 This corresponds to the ``name`` field
750 on the ``request`` instance; if ``request`` is provided, this
751 should not be set.
752 delegates (:class:`MutableSequence[str]`):
753 The sequence of service accounts in a delegation chain.
754 Each service account must be granted the
755 ``roles/iam.serviceAccountTokenCreator`` role on its
756 next service account in the chain. The last service
757 account in the chain must be granted the
758 ``roles/iam.serviceAccountTokenCreator`` role on the
759 service account that is specified in the ``name`` field
760 of the request.
761
762 The delegates must have the following format:
763 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
764 The ``-`` wildcard character is required; replacing it
765 with a project ID is invalid.
766
767 This corresponds to the ``delegates`` field
768 on the ``request`` instance; if ``request`` is provided, this
769 should not be set.
770 payload (:class:`str`):
771 Required. The JWT payload to sign: a
772 JSON object that contains a JWT Claims
773 Set.
774
775 This corresponds to the ``payload`` field
776 on the ``request`` instance; if ``request`` is provided, this
777 should not be set.
778 retry (google.api_core.retry.Retry): Designation of what errors, if any,
779 should be retried.
780 timeout (float): The timeout for this request.
781 metadata (Sequence[Tuple[str, str]]): Strings which should be
782 sent along with the request as metadata.
783
784 Returns:
785 google.cloud.iam_credentials_v1.types.SignJwtResponse:
786
787 """
788 # Create or coerce a protobuf request object.
789 # Quick check: If we got a request object, we should *not* have
790 # gotten any keyword arguments that map to the request.
791 has_flattened_params = any([name, delegates, payload])
792 if request is not None and has_flattened_params:
793 raise ValueError(
794 "If the `request` argument is set, then none of "
795 "the individual field arguments should be set."
796 )
797
798 request = common.SignJwtRequest(request)
799
800 # If we have keyword arguments corresponding to fields on the
801 # request, apply these.
802 if name is not None:
803 request.name = name
804 if payload is not None:
805 request.payload = payload
806 if delegates:
807 request.delegates.extend(delegates)
808
809 # Wrap the RPC method; this adds retry and timeout information,
810 # and friendly error handling.
811 rpc = gapic_v1.method_async.wrap_method(
812 self._client._transport.sign_jwt,
813 default_retry=retries.Retry(
814 initial=0.1,
815 maximum=60.0,
816 multiplier=1.3,
817 predicate=retries.if_exception_type(
818 core_exceptions.DeadlineExceeded,
819 core_exceptions.ServiceUnavailable,
820 ),
821 deadline=60.0,
822 ),
823 default_timeout=60.0,
824 client_info=DEFAULT_CLIENT_INFO,
825 )
826
827 # Certain fields should be provided within the metadata header;
828 # add these here.
829 metadata = tuple(metadata) + (
830 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
831 )
832
833 # Send the request.
834 response = await rpc(
835 request,
836 retry=retry,
837 timeout=timeout,
838 metadata=metadata,
839 )
840
841 # Done; return the response.
842 return response
843
844 async def __aenter__(self) -> "IAMCredentialsAsyncClient":
845 return self
846
847 async def __aexit__(self, exc_type, exc, tb):
848 await self.transport.close()
849
850
851DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
852 gapic_version=package_version.__version__
853)
854
855
856__all__ = ("IAMCredentialsAsyncClient",)