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 os
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29 cast,
30)
31
32from google.api_core import client_options as client_options_lib
33from google.api_core import exceptions as core_exceptions
34from google.api_core import gapic_v1
35from google.api_core import retry as retries
36from google.auth import credentials as ga_credentials # type: ignore
37from google.auth.exceptions import MutualTLSChannelError # type: ignore
38from google.auth.transport import mtls # type: ignore
39from google.auth.transport.grpc import SslCredentials # type: ignore
40from google.oauth2 import service_account # type: ignore
41
42from google.cloud.iam_credentials_v1 import gapic_version as package_version
43
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object] # type: ignore
48
49from google.protobuf import duration_pb2 # type: ignore
50from google.protobuf import timestamp_pb2 # type: ignore
51
52from google.cloud.iam_credentials_v1.types import common
53
54from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport
55from .transports.grpc import IAMCredentialsGrpcTransport
56from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport
57from .transports.rest import IAMCredentialsRestTransport
58
59
60class IAMCredentialsClientMeta(type):
61 """Metaclass for the IAMCredentials client.
62
63 This provides class-level methods for building and retrieving
64 support objects (e.g. transport) without polluting the client instance
65 objects.
66 """
67
68 _transport_registry = (
69 OrderedDict()
70 ) # type: Dict[str, Type[IAMCredentialsTransport]]
71 _transport_registry["grpc"] = IAMCredentialsGrpcTransport
72 _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport
73 _transport_registry["rest"] = IAMCredentialsRestTransport
74
75 def get_transport_class(
76 cls,
77 label: Optional[str] = None,
78 ) -> Type[IAMCredentialsTransport]:
79 """Returns an appropriate transport class.
80
81 Args:
82 label: The name of the desired transport. If none is
83 provided, then the first transport in the registry is used.
84
85 Returns:
86 The transport class to use.
87 """
88 # If a specific transport is requested, return that one.
89 if label:
90 return cls._transport_registry[label]
91
92 # No transport is requested; return the default (that is, the first one
93 # in the dictionary).
94 return next(iter(cls._transport_registry.values()))
95
96
97class IAMCredentialsClient(metaclass=IAMCredentialsClientMeta):
98 """A service account is a special type of Google account that
99 belongs to your application or a virtual machine (VM), instead
100 of to an individual end user. Your application assumes the
101 identity of the service account to call Google APIs, so that the
102 users aren't directly involved.
103
104 Service account credentials are used to temporarily assume the
105 identity of the service account. Supported credential types
106 include OAuth 2.0 access tokens, OpenID Connect ID tokens,
107 self-signed JSON Web Tokens (JWTs), and more.
108 """
109
110 @staticmethod
111 def _get_default_mtls_endpoint(api_endpoint):
112 """Converts api endpoint to mTLS endpoint.
113
114 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
115 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
116 Args:
117 api_endpoint (Optional[str]): the api endpoint to convert.
118 Returns:
119 str: converted mTLS api endpoint.
120 """
121 if not api_endpoint:
122 return api_endpoint
123
124 mtls_endpoint_re = re.compile(
125 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
126 )
127
128 m = mtls_endpoint_re.match(api_endpoint)
129 name, mtls, sandbox, googledomain = m.groups()
130 if mtls or not googledomain:
131 return api_endpoint
132
133 if sandbox:
134 return api_endpoint.replace(
135 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
136 )
137
138 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
139
140 DEFAULT_ENDPOINT = "iamcredentials.googleapis.com"
141 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
142 DEFAULT_ENDPOINT
143 )
144
145 @classmethod
146 def from_service_account_info(cls, info: dict, *args, **kwargs):
147 """Creates an instance of this client using the provided credentials
148 info.
149
150 Args:
151 info (dict): The service account private key info.
152 args: Additional arguments to pass to the constructor.
153 kwargs: Additional arguments to pass to the constructor.
154
155 Returns:
156 IAMCredentialsClient: The constructed client.
157 """
158 credentials = service_account.Credentials.from_service_account_info(info)
159 kwargs["credentials"] = credentials
160 return cls(*args, **kwargs)
161
162 @classmethod
163 def from_service_account_file(cls, filename: str, *args, **kwargs):
164 """Creates an instance of this client using the provided credentials
165 file.
166
167 Args:
168 filename (str): The path to the service account private key json
169 file.
170 args: Additional arguments to pass to the constructor.
171 kwargs: Additional arguments to pass to the constructor.
172
173 Returns:
174 IAMCredentialsClient: The constructed client.
175 """
176 credentials = service_account.Credentials.from_service_account_file(filename)
177 kwargs["credentials"] = credentials
178 return cls(*args, **kwargs)
179
180 from_service_account_json = from_service_account_file
181
182 @property
183 def transport(self) -> IAMCredentialsTransport:
184 """Returns the transport used by the client instance.
185
186 Returns:
187 IAMCredentialsTransport: The transport used by the client
188 instance.
189 """
190 return self._transport
191
192 @staticmethod
193 def service_account_path(
194 project: str,
195 service_account: str,
196 ) -> str:
197 """Returns a fully-qualified service_account string."""
198 return "projects/{project}/serviceAccounts/{service_account}".format(
199 project=project,
200 service_account=service_account,
201 )
202
203 @staticmethod
204 def parse_service_account_path(path: str) -> Dict[str, str]:
205 """Parses a service_account path into its component segments."""
206 m = re.match(
207 r"^projects/(?P<project>.+?)/serviceAccounts/(?P<service_account>.+?)$",
208 path,
209 )
210 return m.groupdict() if m else {}
211
212 @staticmethod
213 def common_billing_account_path(
214 billing_account: str,
215 ) -> str:
216 """Returns a fully-qualified billing_account string."""
217 return "billingAccounts/{billing_account}".format(
218 billing_account=billing_account,
219 )
220
221 @staticmethod
222 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
223 """Parse a billing_account path into its component segments."""
224 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
225 return m.groupdict() if m else {}
226
227 @staticmethod
228 def common_folder_path(
229 folder: str,
230 ) -> str:
231 """Returns a fully-qualified folder string."""
232 return "folders/{folder}".format(
233 folder=folder,
234 )
235
236 @staticmethod
237 def parse_common_folder_path(path: str) -> Dict[str, str]:
238 """Parse a folder path into its component segments."""
239 m = re.match(r"^folders/(?P<folder>.+?)$", path)
240 return m.groupdict() if m else {}
241
242 @staticmethod
243 def common_organization_path(
244 organization: str,
245 ) -> str:
246 """Returns a fully-qualified organization string."""
247 return "organizations/{organization}".format(
248 organization=organization,
249 )
250
251 @staticmethod
252 def parse_common_organization_path(path: str) -> Dict[str, str]:
253 """Parse a organization path into its component segments."""
254 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
255 return m.groupdict() if m else {}
256
257 @staticmethod
258 def common_project_path(
259 project: str,
260 ) -> str:
261 """Returns a fully-qualified project string."""
262 return "projects/{project}".format(
263 project=project,
264 )
265
266 @staticmethod
267 def parse_common_project_path(path: str) -> Dict[str, str]:
268 """Parse a project path into its component segments."""
269 m = re.match(r"^projects/(?P<project>.+?)$", path)
270 return m.groupdict() if m else {}
271
272 @staticmethod
273 def common_location_path(
274 project: str,
275 location: str,
276 ) -> str:
277 """Returns a fully-qualified location string."""
278 return "projects/{project}/locations/{location}".format(
279 project=project,
280 location=location,
281 )
282
283 @staticmethod
284 def parse_common_location_path(path: str) -> Dict[str, str]:
285 """Parse a location path into its component segments."""
286 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
287 return m.groupdict() if m else {}
288
289 @classmethod
290 def get_mtls_endpoint_and_cert_source(
291 cls, client_options: Optional[client_options_lib.ClientOptions] = None
292 ):
293 """Return the API endpoint and client cert source for mutual TLS.
294
295 The client cert source is determined in the following order:
296 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
297 client cert source is None.
298 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
299 default client cert source exists, use the default one; otherwise the client cert
300 source is None.
301
302 The API endpoint is determined in the following order:
303 (1) if `client_options.api_endpoint` if provided, use the provided one.
304 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
305 default mTLS endpoint; if the environment variable is "never", use the default API
306 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
307 use the default API endpoint.
308
309 More details can be found at https://google.aip.dev/auth/4114.
310
311 Args:
312 client_options (google.api_core.client_options.ClientOptions): Custom options for the
313 client. Only the `api_endpoint` and `client_cert_source` properties may be used
314 in this method.
315
316 Returns:
317 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
318 client cert source to use.
319
320 Raises:
321 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
322 """
323 if client_options is None:
324 client_options = client_options_lib.ClientOptions()
325 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
326 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
327 if use_client_cert not in ("true", "false"):
328 raise ValueError(
329 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
330 )
331 if use_mtls_endpoint not in ("auto", "never", "always"):
332 raise MutualTLSChannelError(
333 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
334 )
335
336 # Figure out the client cert source to use.
337 client_cert_source = None
338 if use_client_cert == "true":
339 if client_options.client_cert_source:
340 client_cert_source = client_options.client_cert_source
341 elif mtls.has_default_client_cert_source():
342 client_cert_source = mtls.default_client_cert_source()
343
344 # Figure out which api endpoint to use.
345 if client_options.api_endpoint is not None:
346 api_endpoint = client_options.api_endpoint
347 elif use_mtls_endpoint == "always" or (
348 use_mtls_endpoint == "auto" and client_cert_source
349 ):
350 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
351 else:
352 api_endpoint = cls.DEFAULT_ENDPOINT
353
354 return api_endpoint, client_cert_source
355
356 def __init__(
357 self,
358 *,
359 credentials: Optional[ga_credentials.Credentials] = None,
360 transport: Optional[Union[str, IAMCredentialsTransport]] = None,
361 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
362 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
363 ) -> None:
364 """Instantiates the iam credentials client.
365
366 Args:
367 credentials (Optional[google.auth.credentials.Credentials]): The
368 authorization credentials to attach to requests. These
369 credentials identify the application to the service; if none
370 are specified, the client will attempt to ascertain the
371 credentials from the environment.
372 transport (Union[str, IAMCredentialsTransport]): The
373 transport to use. If set to None, a transport is chosen
374 automatically.
375 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
376 client. It won't take effect if a ``transport`` instance is provided.
377 (1) The ``api_endpoint`` property can be used to override the
378 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
379 environment variable can also be used to override the endpoint:
380 "always" (always use the default mTLS endpoint), "never" (always
381 use the default regular endpoint) and "auto" (auto switch to the
382 default mTLS endpoint if client certificate is present, this is
383 the default value). However, the ``api_endpoint`` property takes
384 precedence if provided.
385 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
386 is "true", then the ``client_cert_source`` property can be used
387 to provide client certificate for mutual TLS transport. If
388 not provided, the default SSL client certificate will be used if
389 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
390 set, no client certificate will be used.
391 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
392 The client info used to send a user-agent string along with
393 API requests. If ``None``, then default info will be used.
394 Generally, you only need to set this if you're developing
395 your own client library.
396
397 Raises:
398 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
399 creation failed for any reason.
400 """
401 if isinstance(client_options, dict):
402 client_options = client_options_lib.from_dict(client_options)
403 if client_options is None:
404 client_options = client_options_lib.ClientOptions()
405 client_options = cast(client_options_lib.ClientOptions, client_options)
406
407 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
408 client_options
409 )
410
411 api_key_value = getattr(client_options, "api_key", None)
412 if api_key_value and credentials:
413 raise ValueError(
414 "client_options.api_key and credentials are mutually exclusive"
415 )
416
417 # Save or instantiate the transport.
418 # Ordinarily, we provide the transport, but allowing a custom transport
419 # instance provides an extensibility point for unusual situations.
420 if isinstance(transport, IAMCredentialsTransport):
421 # transport is a IAMCredentialsTransport instance.
422 if credentials or client_options.credentials_file or api_key_value:
423 raise ValueError(
424 "When providing a transport instance, "
425 "provide its credentials directly."
426 )
427 if client_options.scopes:
428 raise ValueError(
429 "When providing a transport instance, provide its scopes "
430 "directly."
431 )
432 self._transport = transport
433 else:
434 import google.auth._default # type: ignore
435
436 if api_key_value and hasattr(
437 google.auth._default, "get_api_key_credentials"
438 ):
439 credentials = google.auth._default.get_api_key_credentials(
440 api_key_value
441 )
442
443 Transport = type(self).get_transport_class(transport)
444 self._transport = Transport(
445 credentials=credentials,
446 credentials_file=client_options.credentials_file,
447 host=api_endpoint,
448 scopes=client_options.scopes,
449 client_cert_source_for_mtls=client_cert_source_func,
450 quota_project_id=client_options.quota_project_id,
451 client_info=client_info,
452 always_use_jwt_access=True,
453 api_audience=client_options.api_audience,
454 )
455
456 def generate_access_token(
457 self,
458 request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None,
459 *,
460 name: Optional[str] = None,
461 delegates: Optional[MutableSequence[str]] = None,
462 scope: Optional[MutableSequence[str]] = None,
463 lifetime: Optional[duration_pb2.Duration] = None,
464 retry: OptionalRetry = gapic_v1.method.DEFAULT,
465 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
466 metadata: Sequence[Tuple[str, str]] = (),
467 ) -> common.GenerateAccessTokenResponse:
468 r"""Generates an OAuth 2.0 access token for a service
469 account.
470
471 .. code-block:: python
472
473 # This snippet has been automatically generated and should be regarded as a
474 # code template only.
475 # It will require modifications to work:
476 # - It may require correct/in-range values for request initialization.
477 # - It may require specifying regional endpoints when creating the service
478 # client as shown in:
479 # https://googleapis.dev/python/google-api-core/latest/client_options.html
480 from google.cloud import iam_credentials_v1
481
482 def sample_generate_access_token():
483 # Create a client
484 client = iam_credentials_v1.IAMCredentialsClient()
485
486 # Initialize request argument(s)
487 request = iam_credentials_v1.GenerateAccessTokenRequest(
488 name="name_value",
489 scope=['scope_value1', 'scope_value2'],
490 )
491
492 # Make the request
493 response = client.generate_access_token(request=request)
494
495 # Handle the response
496 print(response)
497
498 Args:
499 request (Union[google.cloud.iam_credentials_v1.types.GenerateAccessTokenRequest, dict]):
500 The request object.
501 name (str):
502 Required. The resource name of the service account for
503 which the credentials are requested, in the following
504 format:
505 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
506 The ``-`` wildcard character is required; replacing it
507 with a project ID is invalid.
508
509 This corresponds to the ``name`` field
510 on the ``request`` instance; if ``request`` is provided, this
511 should not be set.
512 delegates (MutableSequence[str]):
513 The sequence of service accounts in a delegation chain.
514 Each service account must be granted the
515 ``roles/iam.serviceAccountTokenCreator`` role on its
516 next service account in the chain. The last service
517 account in the chain must be granted the
518 ``roles/iam.serviceAccountTokenCreator`` role on the
519 service account that is specified in the ``name`` field
520 of the request.
521
522 The delegates must have the following format:
523 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
524 The ``-`` wildcard character is required; replacing it
525 with a project ID is invalid.
526
527 This corresponds to the ``delegates`` field
528 on the ``request`` instance; if ``request`` is provided, this
529 should not be set.
530 scope (MutableSequence[str]):
531 Required. Code to identify the scopes
532 to be included in the OAuth 2.0 access
533 token. See
534 https://developers.google.com/identity/protocols/googlescopes
535 for more information.
536 At least one value required.
537
538 This corresponds to the ``scope`` field
539 on the ``request`` instance; if ``request`` is provided, this
540 should not be set.
541 lifetime (google.protobuf.duration_pb2.Duration):
542 The desired lifetime duration of the
543 access token in seconds. Must be set to
544 a value less than or equal to 3600 (1
545 hour). If a value is not specified, the
546 token's lifetime will be set to a
547 default value of one hour.
548
549 This corresponds to the ``lifetime`` field
550 on the ``request`` instance; if ``request`` is provided, this
551 should not be set.
552 retry (google.api_core.retry.Retry): Designation of what errors, if any,
553 should be retried.
554 timeout (float): The timeout for this request.
555 metadata (Sequence[Tuple[str, str]]): Strings which should be
556 sent along with the request as metadata.
557
558 Returns:
559 google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse:
560
561 """
562 # Create or coerce a protobuf request object.
563 # Quick check: If we got a request object, we should *not* have
564 # gotten any keyword arguments that map to the request.
565 has_flattened_params = any([name, delegates, scope, lifetime])
566 if request is not None and has_flattened_params:
567 raise ValueError(
568 "If the `request` argument is set, then none of "
569 "the individual field arguments should be set."
570 )
571
572 # Minor optimization to avoid making a copy if the user passes
573 # in a common.GenerateAccessTokenRequest.
574 # There's no risk of modifying the input as we've already verified
575 # there are no flattened fields.
576 if not isinstance(request, common.GenerateAccessTokenRequest):
577 request = common.GenerateAccessTokenRequest(request)
578 # If we have keyword arguments corresponding to fields on the
579 # request, apply these.
580 if name is not None:
581 request.name = name
582 if delegates is not None:
583 request.delegates = delegates
584 if scope is not None:
585 request.scope = scope
586 if lifetime is not None:
587 request.lifetime = lifetime
588
589 # Wrap the RPC method; this adds retry and timeout information,
590 # and friendly error handling.
591 rpc = self._transport._wrapped_methods[self._transport.generate_access_token]
592
593 # Certain fields should be provided within the metadata header;
594 # add these here.
595 metadata = tuple(metadata) + (
596 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
597 )
598
599 # Send the request.
600 response = rpc(
601 request,
602 retry=retry,
603 timeout=timeout,
604 metadata=metadata,
605 )
606
607 # Done; return the response.
608 return response
609
610 def generate_id_token(
611 self,
612 request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None,
613 *,
614 name: Optional[str] = None,
615 delegates: Optional[MutableSequence[str]] = None,
616 audience: Optional[str] = None,
617 include_email: Optional[bool] = None,
618 retry: OptionalRetry = gapic_v1.method.DEFAULT,
619 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
620 metadata: Sequence[Tuple[str, str]] = (),
621 ) -> common.GenerateIdTokenResponse:
622 r"""Generates an OpenID Connect ID token for a service
623 account.
624
625 .. code-block:: python
626
627 # This snippet has been automatically generated and should be regarded as a
628 # code template only.
629 # It will require modifications to work:
630 # - It may require correct/in-range values for request initialization.
631 # - It may require specifying regional endpoints when creating the service
632 # client as shown in:
633 # https://googleapis.dev/python/google-api-core/latest/client_options.html
634 from google.cloud import iam_credentials_v1
635
636 def sample_generate_id_token():
637 # Create a client
638 client = iam_credentials_v1.IAMCredentialsClient()
639
640 # Initialize request argument(s)
641 request = iam_credentials_v1.GenerateIdTokenRequest(
642 name="name_value",
643 audience="audience_value",
644 )
645
646 # Make the request
647 response = client.generate_id_token(request=request)
648
649 # Handle the response
650 print(response)
651
652 Args:
653 request (Union[google.cloud.iam_credentials_v1.types.GenerateIdTokenRequest, dict]):
654 The request object.
655 name (str):
656 Required. The resource name of the service account for
657 which the credentials are requested, in the following
658 format:
659 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
660 The ``-`` wildcard character is required; replacing it
661 with a project ID is invalid.
662
663 This corresponds to the ``name`` field
664 on the ``request`` instance; if ``request`` is provided, this
665 should not be set.
666 delegates (MutableSequence[str]):
667 The sequence of service accounts in a delegation chain.
668 Each service account must be granted the
669 ``roles/iam.serviceAccountTokenCreator`` role on its
670 next service account in the chain. The last service
671 account in the chain must be granted the
672 ``roles/iam.serviceAccountTokenCreator`` role on the
673 service account that is specified in the ``name`` field
674 of the request.
675
676 The delegates must have the following format:
677 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
678 The ``-`` wildcard character is required; replacing it
679 with a project ID is invalid.
680
681 This corresponds to the ``delegates`` field
682 on the ``request`` instance; if ``request`` is provided, this
683 should not be set.
684 audience (str):
685 Required. The audience for the token,
686 such as the API or account that this
687 token grants access to.
688
689 This corresponds to the ``audience`` field
690 on the ``request`` instance; if ``request`` is provided, this
691 should not be set.
692 include_email (bool):
693 Include the service account email in the token. If set
694 to ``true``, the token will contain ``email`` and
695 ``email_verified`` claims.
696
697 This corresponds to the ``include_email`` field
698 on the ``request`` instance; if ``request`` is provided, this
699 should not be set.
700 retry (google.api_core.retry.Retry): Designation of what errors, if any,
701 should be retried.
702 timeout (float): The timeout for this request.
703 metadata (Sequence[Tuple[str, str]]): Strings which should be
704 sent along with the request as metadata.
705
706 Returns:
707 google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse:
708
709 """
710 # Create or coerce a protobuf request object.
711 # Quick check: If we got a request object, we should *not* have
712 # gotten any keyword arguments that map to the request.
713 has_flattened_params = any([name, delegates, audience, include_email])
714 if request is not None and has_flattened_params:
715 raise ValueError(
716 "If the `request` argument is set, then none of "
717 "the individual field arguments should be set."
718 )
719
720 # Minor optimization to avoid making a copy if the user passes
721 # in a common.GenerateIdTokenRequest.
722 # There's no risk of modifying the input as we've already verified
723 # there are no flattened fields.
724 if not isinstance(request, common.GenerateIdTokenRequest):
725 request = common.GenerateIdTokenRequest(request)
726 # If we have keyword arguments corresponding to fields on the
727 # request, apply these.
728 if name is not None:
729 request.name = name
730 if delegates is not None:
731 request.delegates = delegates
732 if audience is not None:
733 request.audience = audience
734 if include_email is not None:
735 request.include_email = include_email
736
737 # Wrap the RPC method; this adds retry and timeout information,
738 # and friendly error handling.
739 rpc = self._transport._wrapped_methods[self._transport.generate_id_token]
740
741 # Certain fields should be provided within the metadata header;
742 # add these here.
743 metadata = tuple(metadata) + (
744 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
745 )
746
747 # Send the request.
748 response = rpc(
749 request,
750 retry=retry,
751 timeout=timeout,
752 metadata=metadata,
753 )
754
755 # Done; return the response.
756 return response
757
758 def sign_blob(
759 self,
760 request: Optional[Union[common.SignBlobRequest, dict]] = None,
761 *,
762 name: Optional[str] = None,
763 delegates: Optional[MutableSequence[str]] = None,
764 payload: Optional[bytes] = None,
765 retry: OptionalRetry = gapic_v1.method.DEFAULT,
766 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
767 metadata: Sequence[Tuple[str, str]] = (),
768 ) -> common.SignBlobResponse:
769 r"""Signs a blob using a service account's system-managed
770 private key.
771
772 .. code-block:: python
773
774 # This snippet has been automatically generated and should be regarded as a
775 # code template only.
776 # It will require modifications to work:
777 # - It may require correct/in-range values for request initialization.
778 # - It may require specifying regional endpoints when creating the service
779 # client as shown in:
780 # https://googleapis.dev/python/google-api-core/latest/client_options.html
781 from google.cloud import iam_credentials_v1
782
783 def sample_sign_blob():
784 # Create a client
785 client = iam_credentials_v1.IAMCredentialsClient()
786
787 # Initialize request argument(s)
788 request = iam_credentials_v1.SignBlobRequest(
789 name="name_value",
790 payload=b'payload_blob',
791 )
792
793 # Make the request
794 response = client.sign_blob(request=request)
795
796 # Handle the response
797 print(response)
798
799 Args:
800 request (Union[google.cloud.iam_credentials_v1.types.SignBlobRequest, dict]):
801 The request object.
802 name (str):
803 Required. The resource name of the service account for
804 which the credentials are requested, in the following
805 format:
806 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
807 The ``-`` wildcard character is required; replacing it
808 with a project ID is invalid.
809
810 This corresponds to the ``name`` field
811 on the ``request`` instance; if ``request`` is provided, this
812 should not be set.
813 delegates (MutableSequence[str]):
814 The sequence of service accounts in a delegation chain.
815 Each service account must be granted the
816 ``roles/iam.serviceAccountTokenCreator`` role on its
817 next service account in the chain. The last service
818 account in the chain must be granted the
819 ``roles/iam.serviceAccountTokenCreator`` role on the
820 service account that is specified in the ``name`` field
821 of the request.
822
823 The delegates must have the following format:
824 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
825 The ``-`` wildcard character is required; replacing it
826 with a project ID is invalid.
827
828 This corresponds to the ``delegates`` field
829 on the ``request`` instance; if ``request`` is provided, this
830 should not be set.
831 payload (bytes):
832 Required. The bytes to sign.
833 This corresponds to the ``payload`` field
834 on the ``request`` instance; if ``request`` is provided, this
835 should not be set.
836 retry (google.api_core.retry.Retry): Designation of what errors, if any,
837 should be retried.
838 timeout (float): The timeout for this request.
839 metadata (Sequence[Tuple[str, str]]): Strings which should be
840 sent along with the request as metadata.
841
842 Returns:
843 google.cloud.iam_credentials_v1.types.SignBlobResponse:
844
845 """
846 # Create or coerce a protobuf request object.
847 # Quick check: If we got a request object, we should *not* have
848 # gotten any keyword arguments that map to the request.
849 has_flattened_params = any([name, delegates, payload])
850 if request is not None and has_flattened_params:
851 raise ValueError(
852 "If the `request` argument is set, then none of "
853 "the individual field arguments should be set."
854 )
855
856 # Minor optimization to avoid making a copy if the user passes
857 # in a common.SignBlobRequest.
858 # There's no risk of modifying the input as we've already verified
859 # there are no flattened fields.
860 if not isinstance(request, common.SignBlobRequest):
861 request = common.SignBlobRequest(request)
862 # If we have keyword arguments corresponding to fields on the
863 # request, apply these.
864 if name is not None:
865 request.name = name
866 if delegates is not None:
867 request.delegates = delegates
868 if payload is not None:
869 request.payload = payload
870
871 # Wrap the RPC method; this adds retry and timeout information,
872 # and friendly error handling.
873 rpc = self._transport._wrapped_methods[self._transport.sign_blob]
874
875 # Certain fields should be provided within the metadata header;
876 # add these here.
877 metadata = tuple(metadata) + (
878 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
879 )
880
881 # Send the request.
882 response = rpc(
883 request,
884 retry=retry,
885 timeout=timeout,
886 metadata=metadata,
887 )
888
889 # Done; return the response.
890 return response
891
892 def sign_jwt(
893 self,
894 request: Optional[Union[common.SignJwtRequest, dict]] = None,
895 *,
896 name: Optional[str] = None,
897 delegates: Optional[MutableSequence[str]] = None,
898 payload: Optional[str] = None,
899 retry: OptionalRetry = gapic_v1.method.DEFAULT,
900 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
901 metadata: Sequence[Tuple[str, str]] = (),
902 ) -> common.SignJwtResponse:
903 r"""Signs a JWT using a service account's system-managed
904 private key.
905
906 .. code-block:: python
907
908 # This snippet has been automatically generated and should be regarded as a
909 # code template only.
910 # It will require modifications to work:
911 # - It may require correct/in-range values for request initialization.
912 # - It may require specifying regional endpoints when creating the service
913 # client as shown in:
914 # https://googleapis.dev/python/google-api-core/latest/client_options.html
915 from google.cloud import iam_credentials_v1
916
917 def sample_sign_jwt():
918 # Create a client
919 client = iam_credentials_v1.IAMCredentialsClient()
920
921 # Initialize request argument(s)
922 request = iam_credentials_v1.SignJwtRequest(
923 name="name_value",
924 payload="payload_value",
925 )
926
927 # Make the request
928 response = client.sign_jwt(request=request)
929
930 # Handle the response
931 print(response)
932
933 Args:
934 request (Union[google.cloud.iam_credentials_v1.types.SignJwtRequest, dict]):
935 The request object.
936 name (str):
937 Required. The resource name of the service account for
938 which the credentials are requested, in the following
939 format:
940 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
941 The ``-`` wildcard character is required; replacing it
942 with a project ID is invalid.
943
944 This corresponds to the ``name`` field
945 on the ``request`` instance; if ``request`` is provided, this
946 should not be set.
947 delegates (MutableSequence[str]):
948 The sequence of service accounts in a delegation chain.
949 Each service account must be granted the
950 ``roles/iam.serviceAccountTokenCreator`` role on its
951 next service account in the chain. The last service
952 account in the chain must be granted the
953 ``roles/iam.serviceAccountTokenCreator`` role on the
954 service account that is specified in the ``name`` field
955 of the request.
956
957 The delegates must have the following format:
958 ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
959 The ``-`` wildcard character is required; replacing it
960 with a project ID is invalid.
961
962 This corresponds to the ``delegates`` field
963 on the ``request`` instance; if ``request`` is provided, this
964 should not be set.
965 payload (str):
966 Required. The JWT payload to sign: a
967 JSON object that contains a JWT Claims
968 Set.
969
970 This corresponds to the ``payload`` field
971 on the ``request`` instance; if ``request`` is provided, this
972 should not be set.
973 retry (google.api_core.retry.Retry): Designation of what errors, if any,
974 should be retried.
975 timeout (float): The timeout for this request.
976 metadata (Sequence[Tuple[str, str]]): Strings which should be
977 sent along with the request as metadata.
978
979 Returns:
980 google.cloud.iam_credentials_v1.types.SignJwtResponse:
981
982 """
983 # Create or coerce a protobuf request object.
984 # Quick check: If we got a request object, we should *not* have
985 # gotten any keyword arguments that map to the request.
986 has_flattened_params = any([name, delegates, payload])
987 if request is not None and has_flattened_params:
988 raise ValueError(
989 "If the `request` argument is set, then none of "
990 "the individual field arguments should be set."
991 )
992
993 # Minor optimization to avoid making a copy if the user passes
994 # in a common.SignJwtRequest.
995 # There's no risk of modifying the input as we've already verified
996 # there are no flattened fields.
997 if not isinstance(request, common.SignJwtRequest):
998 request = common.SignJwtRequest(request)
999 # If we have keyword arguments corresponding to fields on the
1000 # request, apply these.
1001 if name is not None:
1002 request.name = name
1003 if delegates is not None:
1004 request.delegates = delegates
1005 if payload is not None:
1006 request.payload = payload
1007
1008 # Wrap the RPC method; this adds retry and timeout information,
1009 # and friendly error handling.
1010 rpc = self._transport._wrapped_methods[self._transport.sign_jwt]
1011
1012 # Certain fields should be provided within the metadata header;
1013 # add these here.
1014 metadata = tuple(metadata) + (
1015 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1016 )
1017
1018 # Send the request.
1019 response = rpc(
1020 request,
1021 retry=retry,
1022 timeout=timeout,
1023 metadata=metadata,
1024 )
1025
1026 # Done; return the response.
1027 return response
1028
1029 def __enter__(self) -> "IAMCredentialsClient":
1030 return self
1031
1032 def __exit__(self, type, value, traceback):
1033 """Releases underlying transport's resources.
1034
1035 .. warning::
1036 ONLY use as a context manager if the transport is NOT shared
1037 with other clients! Exiting the with block will CLOSE the transport
1038 and may cause errors in other clients!
1039 """
1040 self.transport.close()
1041
1042
1043DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1044 gapic_version=package_version.__version__
1045)
1046
1047
1048__all__ = ("IAMCredentialsClient",)