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

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

265 statements  

1# -*- coding: utf-8 -*- 

2# Copyright 2026 Google LLC 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15# 

16import json 

17import logging as std_logging 

18import os 

19import re 

20import warnings 

21from collections import OrderedDict 

22from http import HTTPStatus 

23from typing import ( 

24 Callable, 

25 Dict, 

26 Mapping, 

27 MutableMapping, 

28 MutableSequence, 

29 Optional, 

30 Sequence, 

31 Tuple, 

32 Type, 

33 Union, 

34 cast, 

35) 

36 

37import google.protobuf 

38from google.api_core import client_options as client_options_lib 

39from google.api_core import exceptions as core_exceptions 

40from google.api_core import gapic_v1 

41from google.api_core import retry as retries 

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

43from google.auth.exceptions import MutualTLSChannelError # type: ignore 

44from google.auth.transport import mtls # type: ignore 

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

46from google.oauth2 import service_account # type: ignore 

47 

48from google.cloud.iam_credentials_v1 import gapic_version as package_version 

49from google.cloud.iam_credentials_v1._compat import ( 

50 get_api_endpoint, 

51 get_default_mtls_endpoint, 

52 get_universe_domain, 

53 read_environment_variables, 

54 should_use_client_cert, 

55) 

56 

57try: 

58 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 

59except AttributeError: # pragma: NO COVER 

60 OptionalRetry = Union[retries.Retry, object, None] # type: ignore 

61 

62try: 

63 from google.api_core import client_logging # type: ignore 

64 

65 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

66except ImportError: # pragma: NO COVER 

67 CLIENT_LOGGING_SUPPORTED = False 

68 

69_LOGGER = std_logging.getLogger(__name__) 

70 

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

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

73 

74from google.cloud.iam_credentials_v1.types import common 

75 

76from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport 

77from .transports.grpc import IAMCredentialsGrpcTransport 

78from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport 

79from .transports.rest import IAMCredentialsRestTransport 

80 

81 

82class IAMCredentialsClientMeta(type): 

83 """Metaclass for the IAMCredentials client. 

84 

85 This provides class-level methods for building and retrieving 

86 support objects (e.g. transport) without polluting the client instance 

87 objects. 

88 """ 

89 

90 _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] 

91 _transport_registry["grpc"] = IAMCredentialsGrpcTransport 

92 _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport 

93 _transport_registry["rest"] = IAMCredentialsRestTransport 

94 

95 def get_transport_class( 

96 cls, 

97 label: Optional[str] = None, 

98 ) -> Type[IAMCredentialsTransport]: 

99 """Returns an appropriate transport class. 

100 

101 Args: 

102 label: The name of the desired transport. If none is 

103 provided, then the first transport in the registry is used. 

104 

105 Returns: 

106 The transport class to use. 

107 """ 

108 # If a specific transport is requested, return that one. 

109 if label: 

110 return cls._transport_registry[label] 

111 

112 # No transport is requested; return the default (that is, the first one 

113 # in the dictionary). 

114 return next(iter(cls._transport_registry.values())) 

115 

116 

117class IAMCredentialsClient(metaclass=IAMCredentialsClientMeta): 

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

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

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

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

122 users aren't directly involved. 

123 

124 Service account credentials are used to temporarily assume the 

125 identity of the service account. Supported credential types 

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

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

128 """ 

129 

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

131 DEFAULT_ENDPOINT = "iamcredentials.googleapis.com" 

132 DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) 

133 

134 _DEFAULT_ENDPOINT_TEMPLATE = "iamcredentials.{UNIVERSE_DOMAIN}" 

135 _DEFAULT_UNIVERSE = "googleapis.com" 

136 

137 @classmethod 

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

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

140 info. 

141 

142 Args: 

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

144 args: Additional arguments to pass to the constructor. 

145 kwargs: Additional arguments to pass to the constructor. 

146 

147 Returns: 

148 IAMCredentialsClient: The constructed client. 

149 """ 

150 credentials = service_account.Credentials.from_service_account_info(info) 

151 kwargs["credentials"] = credentials 

152 return cls(*args, **kwargs) 

153 

154 @classmethod 

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

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

157 file. 

158 

159 Args: 

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

161 file. 

162 args: Additional arguments to pass to the constructor. 

163 kwargs: Additional arguments to pass to the constructor. 

164 

165 Returns: 

166 IAMCredentialsClient: The constructed client. 

167 """ 

168 credentials = service_account.Credentials.from_service_account_file(filename) 

169 kwargs["credentials"] = credentials 

170 return cls(*args, **kwargs) 

171 

172 from_service_account_json = from_service_account_file 

173 

174 @property 

175 def transport(self) -> IAMCredentialsTransport: 

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

177 

178 Returns: 

179 IAMCredentialsTransport: The transport used by the client 

180 instance. 

181 """ 

182 return self._transport 

183 

184 @staticmethod 

185 def service_account_path( 

186 project: str, 

187 service_account: str, 

188 ) -> str: 

189 """Returns a fully-qualified service_account string.""" 

190 return "projects/{project}/serviceAccounts/{service_account}".format( 

191 project=project, 

192 service_account=service_account, 

193 ) 

194 

195 @staticmethod 

196 def parse_service_account_path(path: str) -> Dict[str, str]: 

197 """Parses a service_account path into its component segments.""" 

198 m = re.match( 

199 r"^projects/(?P<project>.+?)/serviceAccounts/(?P<service_account>.+?)$", 

200 path, 

201 ) 

202 return m.groupdict() if m else {} 

203 

204 @staticmethod 

205 def common_billing_account_path( 

206 billing_account: str, 

207 ) -> str: 

208 """Returns a fully-qualified billing_account string.""" 

209 return "billingAccounts/{billing_account}".format( 

210 billing_account=billing_account, 

211 ) 

212 

213 @staticmethod 

214 def parse_common_billing_account_path(path: str) -> Dict[str, str]: 

215 """Parse a billing_account path into its component segments.""" 

216 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) 

217 return m.groupdict() if m else {} 

218 

219 @staticmethod 

220 def common_folder_path( 

221 folder: str, 

222 ) -> str: 

223 """Returns a fully-qualified folder string.""" 

224 return "folders/{folder}".format( 

225 folder=folder, 

226 ) 

227 

228 @staticmethod 

229 def parse_common_folder_path(path: str) -> Dict[str, str]: 

230 """Parse a folder path into its component segments.""" 

231 m = re.match(r"^folders/(?P<folder>.+?)$", path) 

232 return m.groupdict() if m else {} 

233 

234 @staticmethod 

235 def common_organization_path( 

236 organization: str, 

237 ) -> str: 

238 """Returns a fully-qualified organization string.""" 

239 return "organizations/{organization}".format( 

240 organization=organization, 

241 ) 

242 

243 @staticmethod 

244 def parse_common_organization_path(path: str) -> Dict[str, str]: 

245 """Parse a organization path into its component segments.""" 

246 m = re.match(r"^organizations/(?P<organization>.+?)$", path) 

247 return m.groupdict() if m else {} 

248 

249 @staticmethod 

250 def common_project_path( 

251 project: str, 

252 ) -> str: 

253 """Returns a fully-qualified project string.""" 

254 return "projects/{project}".format( 

255 project=project, 

256 ) 

257 

258 @staticmethod 

259 def parse_common_project_path(path: str) -> Dict[str, str]: 

260 """Parse a project path into its component segments.""" 

261 m = re.match(r"^projects/(?P<project>.+?)$", path) 

262 return m.groupdict() if m else {} 

263 

264 @staticmethod 

265 def common_location_path( 

266 project: str, 

267 location: str, 

268 ) -> str: 

269 """Returns a fully-qualified location string.""" 

270 return "projects/{project}/locations/{location}".format( 

271 project=project, 

272 location=location, 

273 ) 

274 

275 @staticmethod 

276 def parse_common_location_path(path: str) -> Dict[str, str]: 

277 """Parse a location path into its component segments.""" 

278 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) 

279 return m.groupdict() if m else {} 

280 

281 @classmethod 

282 def get_mtls_endpoint_and_cert_source( 

283 cls, client_options: Optional[client_options_lib.ClientOptions] = None 

284 ): 

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

286 

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

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

289 client cert source is None. 

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

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

292 source is None. 

293 

294 The API endpoint is determined in the following order: 

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

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

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

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

299 use the default API endpoint. 

300 

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

302 

303 Args: 

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

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

306 in this method. 

307 

308 Returns: 

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

310 client cert source to use. 

311 

312 Raises: 

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

314 """ 

315 

316 warnings.warn( 

317 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", 

318 DeprecationWarning, 

319 ) 

320 if client_options is None: 

321 client_options = client_options_lib.ClientOptions() 

322 use_client_cert = should_use_client_cert() 

323 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") 

324 if use_mtls_endpoint not in ("auto", "never", "always"): 

325 raise MutualTLSChannelError( 

326 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

327 ) 

328 

329 # Figure out the client cert source to use. 

330 client_cert_source = None 

331 if use_client_cert: 

332 if client_options.client_cert_source: 

333 client_cert_source = client_options.client_cert_source 

334 elif mtls.has_default_client_cert_source(): 

335 client_cert_source = mtls.default_client_cert_source() 

336 

337 # Figure out which api endpoint to use. 

338 if client_options.api_endpoint is not None: 

339 api_endpoint = client_options.api_endpoint 

340 elif use_mtls_endpoint == "always" or ( 

341 use_mtls_endpoint == "auto" and client_cert_source 

342 ): 

343 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore 

344 else: 

345 api_endpoint = cls.DEFAULT_ENDPOINT 

346 

347 return api_endpoint, client_cert_source 

348 

349 @staticmethod 

350 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

351 """Return the client cert source to be used by the client. 

352 

353 Args: 

354 provided_cert_source (bytes): The client certificate source provided. 

355 use_cert_flag (bool): A flag indicating whether to use the client certificate. 

356 

357 Returns: 

358 bytes or None: The client cert source to be used by the client. 

359 """ 

360 client_cert_source = None 

361 if use_cert_flag: 

362 if provided_cert_source: 

363 client_cert_source = provided_cert_source 

364 elif mtls.has_default_client_cert_source(): 

365 client_cert_source = mtls.default_client_cert_source() 

366 return client_cert_source 

367 

368 def _validate_universe_domain(self): 

369 """Validates client's and credentials' universe domains are consistent. 

370 

371 Returns: 

372 bool: True iff the configured universe domain is valid. 

373 

374 Raises: 

375 ValueError: If the configured universe domain is not valid. 

376 """ 

377 

378 # NOTE (b/349488459): universe validation is disabled until further notice. 

379 return True 

380 

381 def _add_cred_info_for_auth_errors( 

382 self, error: core_exceptions.GoogleAPICallError 

383 ) -> None: 

384 """Adds credential info string to error details for 401/403/404 errors. 

385 

386 Args: 

387 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. 

388 """ 

389 if error.code not in [ 

390 HTTPStatus.UNAUTHORIZED, 

391 HTTPStatus.FORBIDDEN, 

392 HTTPStatus.NOT_FOUND, 

393 ]: 

394 return 

395 

396 cred = self._transport._credentials 

397 

398 # get_cred_info is only available in google-auth>=2.35.0 

399 if not hasattr(cred, "get_cred_info"): 

400 return 

401 

402 # ignore the type check since pypy test fails when get_cred_info 

403 # is not available 

404 cred_info = cred.get_cred_info() # type: ignore 

405 if cred_info and hasattr(error._details, "append"): 

406 error._details.append(json.dumps(cred_info)) 

407 

408 @property 

409 def api_endpoint(self) -> str: 

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

411 

412 Returns: 

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

414 """ 

415 return self._api_endpoint 

416 

417 @property 

418 def universe_domain(self) -> str: 

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

420 

421 Returns: 

422 str: The universe domain used by the client instance. 

423 """ 

424 return self._universe_domain 

425 

426 def __init__( 

427 self, 

428 *, 

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

430 transport: Optional[ 

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

432 ] = None, 

433 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, 

434 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

435 ) -> None: 

436 """Instantiates the iam credentials client. 

437 

438 Args: 

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

440 authorization credentials to attach to requests. These 

441 credentials identify the application to the service; if none 

442 are specified, the client will attempt to ascertain the 

443 credentials from the environment. 

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

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

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

447 arguments as used in the IAMCredentialsTransport constructor. 

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

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

450 Custom options for the client. 

451 

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

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

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

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

456 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

457 variable, which have one of the following values: 

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

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

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

461 the default value). 

462 

463 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

465 to provide a client certificate for mTLS transport. If 

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

467 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

468 set, no client certificate will be used. 

469 

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

471 default "googleapis.com" universe. Note that the ``api_endpoint`` 

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

473 currently not supported for mTLS. 

474 

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

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

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

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

479 your own client library. 

480 

481 Raises: 

482 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport 

483 creation failed for any reason. 

484 """ 

485 self._client_options = client_options 

486 if isinstance(self._client_options, dict): 

487 self._client_options = client_options_lib.from_dict(self._client_options) 

488 if self._client_options is None: 

489 self._client_options = client_options_lib.ClientOptions() 

490 self._client_options = cast( 

491 client_options_lib.ClientOptions, self._client_options 

492 ) 

493 

494 universe_domain_opt = getattr(self._client_options, "universe_domain", None) 

495 

496 self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( 

497 read_environment_variables() 

498 ) 

499 self._client_cert_source = IAMCredentialsClient._get_client_cert_source( 

500 self._client_options.client_cert_source, self._use_client_cert 

501 ) 

502 self._universe_domain = get_universe_domain( 

503 universe_domain_opt, 

504 self._universe_domain_env, 

505 default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, 

506 ) 

507 self._api_endpoint: str = "" # updated below, depending on `transport` 

508 

509 # Initialize the universe domain validation. 

510 self._is_universe_domain_valid = False 

511 

512 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

513 # Setup logging. 

514 client_logging.initialize_logging() 

515 

516 api_key_value = getattr(self._client_options, "api_key", None) 

517 if api_key_value and credentials: 

518 raise ValueError( 

519 "client_options.api_key and credentials are mutually exclusive" 

520 ) 

521 

522 # Save or instantiate the transport. 

523 # Ordinarily, we provide the transport, but allowing a custom transport 

524 # instance provides an extensibility point for unusual situations. 

525 transport_provided = isinstance(transport, IAMCredentialsTransport) 

526 if transport_provided: 

527 # transport is a IAMCredentialsTransport instance. 

528 if credentials or self._client_options.credentials_file or api_key_value: 

529 raise ValueError( 

530 "When providing a transport instance, " 

531 "provide its credentials directly." 

532 ) 

533 if self._client_options.scopes: 

534 raise ValueError( 

535 "When providing a transport instance, provide its scopes directly." 

536 ) 

537 self._transport = cast(IAMCredentialsTransport, transport) 

538 self._api_endpoint = self._transport.host 

539 

540 self._api_endpoint = self._api_endpoint or get_api_endpoint( 

541 api_override=self._client_options.api_endpoint, 

542 universe_domain=self._universe_domain, 

543 default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, 

544 default_mtls_endpoint=IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT, 

545 default_endpoint_template=IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE, 

546 use_mtls=self._use_mtls_endpoint == "always" 

547 or (self._use_mtls_endpoint == "auto" and self._client_cert_source), 

548 ) 

549 

550 if not transport_provided: 

551 import google.auth._default # type: ignore 

552 

553 if api_key_value and hasattr( 

554 google.auth._default, "get_api_key_credentials" 

555 ): 

556 credentials = google.auth._default.get_api_key_credentials( 

557 api_key_value 

558 ) 

559 

560 transport_init: Union[ 

561 Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] 

562 ] = ( 

563 IAMCredentialsClient.get_transport_class(transport) 

564 if isinstance(transport, str) or transport is None 

565 else cast(Callable[..., IAMCredentialsTransport], transport) 

566 ) 

567 # initialize with the provided callable or the passed in class 

568 self._transport = transport_init( 

569 credentials=credentials, 

570 credentials_file=self._client_options.credentials_file, 

571 host=self._api_endpoint, 

572 scopes=self._client_options.scopes, 

573 client_cert_source_for_mtls=self._client_cert_source, 

574 quota_project_id=self._client_options.quota_project_id, 

575 client_info=client_info, 

576 always_use_jwt_access=True, 

577 api_audience=self._client_options.api_audience, 

578 ) 

579 

580 if "async" not in str(self._transport): 

581 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

582 std_logging.DEBUG 

583 ): # pragma: NO COVER 

584 _LOGGER.debug( 

585 "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", 

586 extra={ 

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

588 "universeDomain": getattr( 

589 self._transport._credentials, "universe_domain", "" 

590 ), 

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

592 "credentialsInfo": getattr( 

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

594 )(), 

595 } 

596 if hasattr(self._transport, "_credentials") 

597 else { 

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

599 "credentialsType": None, 

600 }, 

601 ) 

602 

603 def generate_access_token( 

604 self, 

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

606 *, 

607 name: Optional[str] = None, 

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

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

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

611 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

614 ) -> common.GenerateAccessTokenResponse: 

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

616 account. 

617 

618 .. code-block:: python 

619 

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

621 # code template only. 

622 # It will require modifications to work: 

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

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

625 # client as shown in: 

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

627 from google.cloud import iam_credentials_v1 

628 

629 def sample_generate_access_token(): 

630 # Create a client 

631 client = iam_credentials_v1.IAMCredentialsClient() 

632 

633 # Initialize request argument(s) 

634 request = iam_credentials_v1.GenerateAccessTokenRequest( 

635 name="name_value", 

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

637 ) 

638 

639 # Make the request 

640 response = client.generate_access_token(request=request) 

641 

642 # Handle the response 

643 print(response) 

644 

645 Args: 

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

647 The request object. 

648 name (str): 

649 Required. The resource name of the service account for 

650 which the credentials are requested, in the following 

651 format: 

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

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

654 with a project ID is invalid. 

655 

656 This corresponds to the ``name`` field 

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

658 should not be set. 

659 delegates (MutableSequence[str]): 

660 The sequence of service accounts in a delegation chain. 

661 Each service account must be granted the 

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

663 next service account in the chain. The last service 

664 account in the chain must be granted the 

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

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

667 of the request. 

668 

669 The delegates must have the following format: 

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

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

672 with a project ID is invalid. 

673 

674 This corresponds to the ``delegates`` field 

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

676 should not be set. 

677 scope (MutableSequence[str]): 

678 Required. Code to identify the scopes 

679 to be included in the OAuth 2.0 access 

680 token. See 

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

682 for more information. 

683 At least one value required. 

684 

685 This corresponds to the ``scope`` field 

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

687 should not be set. 

688 lifetime (google.protobuf.duration_pb2.Duration): 

689 The desired lifetime duration of the 

690 access token in seconds. Must be set to 

691 a value less than or equal to 3600 (1 

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

693 token's lifetime will be set to a 

694 default value of one hour. 

695 

696 This corresponds to the ``lifetime`` field 

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

698 should not be set. 

699 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

700 should be retried. 

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

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

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

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

705 be of type `bytes`. 

706 

707 Returns: 

708 google.cloud.iam_credentials_v1.types.GenerateAccessTokenResponse: 

709 

710 """ 

711 # Create or coerce a protobuf request object. 

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

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

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

715 has_flattened_params = ( 

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

717 ) 

718 if request is not None and has_flattened_params: 

719 raise ValueError( 

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

721 "the individual field arguments should be set." 

722 ) 

723 

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

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

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

727 request = common.GenerateAccessTokenRequest(request) 

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

729 # request, apply these. 

730 if name is not None: 

731 request.name = name 

732 if delegates is not None: 

733 request.delegates = delegates 

734 if scope is not None: 

735 request.scope = scope 

736 if lifetime is not None: 

737 request.lifetime = lifetime 

738 

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

740 # and friendly error handling. 

741 rpc = self._transport._wrapped_methods[self._transport.generate_access_token] 

742 

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

744 # add these here. 

745 metadata = tuple(metadata) + ( 

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

747 ) 

748 

749 # Validate the universe domain. 

750 self._validate_universe_domain() 

751 

752 # Send the request. 

753 response = rpc( 

754 request, 

755 retry=retry, 

756 timeout=timeout, 

757 metadata=metadata, 

758 ) 

759 

760 # Done; return the response. 

761 return response 

762 

763 def generate_id_token( 

764 self, 

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

766 *, 

767 name: Optional[str] = None, 

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

769 audience: Optional[str] = None, 

770 include_email: Optional[bool] = None, 

771 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

774 ) -> common.GenerateIdTokenResponse: 

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

776 account. 

777 

778 .. code-block:: python 

779 

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

781 # code template only. 

782 # It will require modifications to work: 

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

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

785 # client as shown in: 

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

787 from google.cloud import iam_credentials_v1 

788 

789 def sample_generate_id_token(): 

790 # Create a client 

791 client = iam_credentials_v1.IAMCredentialsClient() 

792 

793 # Initialize request argument(s) 

794 request = iam_credentials_v1.GenerateIdTokenRequest( 

795 name="name_value", 

796 audience="audience_value", 

797 ) 

798 

799 # Make the request 

800 response = client.generate_id_token(request=request) 

801 

802 # Handle the response 

803 print(response) 

804 

805 Args: 

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

807 The request object. 

808 name (str): 

809 Required. The resource name of the service account for 

810 which the credentials are requested, in the following 

811 format: 

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

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

814 with a project ID is invalid. 

815 

816 This corresponds to the ``name`` field 

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

818 should not be set. 

819 delegates (MutableSequence[str]): 

820 The sequence of service accounts in a delegation chain. 

821 Each service account must be granted the 

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

823 next service account in the chain. The last service 

824 account in the chain must be granted the 

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

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

827 of the request. 

828 

829 The delegates must have the following format: 

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

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

832 with a project ID is invalid. 

833 

834 This corresponds to the ``delegates`` field 

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

836 should not be set. 

837 audience (str): 

838 Required. The audience for the token, 

839 such as the API or account that this 

840 token grants access to. 

841 

842 This corresponds to the ``audience`` field 

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

844 should not be set. 

845 include_email (bool): 

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

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

848 ``email_verified`` claims. 

849 

850 This corresponds to the ``include_email`` field 

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

852 should not be set. 

853 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

854 should be retried. 

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

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

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

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

859 be of type `bytes`. 

860 

861 Returns: 

862 google.cloud.iam_credentials_v1.types.GenerateIdTokenResponse: 

863 

864 """ 

865 # Create or coerce a protobuf request object. 

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

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

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

869 has_flattened_params = ( 

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

871 ) 

872 if request is not None and has_flattened_params: 

873 raise ValueError( 

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

875 "the individual field arguments should be set." 

876 ) 

877 

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

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

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

881 request = common.GenerateIdTokenRequest(request) 

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

883 # request, apply these. 

884 if name is not None: 

885 request.name = name 

886 if delegates is not None: 

887 request.delegates = delegates 

888 if audience is not None: 

889 request.audience = audience 

890 if include_email is not None: 

891 request.include_email = include_email 

892 

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

894 # and friendly error handling. 

895 rpc = self._transport._wrapped_methods[self._transport.generate_id_token] 

896 

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

898 # add these here. 

899 metadata = tuple(metadata) + ( 

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

901 ) 

902 

903 # Validate the universe domain. 

904 self._validate_universe_domain() 

905 

906 # Send the request. 

907 response = rpc( 

908 request, 

909 retry=retry, 

910 timeout=timeout, 

911 metadata=metadata, 

912 ) 

913 

914 # Done; return the response. 

915 return response 

916 

917 def sign_blob( 

918 self, 

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

920 *, 

921 name: Optional[str] = None, 

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

923 payload: Optional[bytes] = None, 

924 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

927 ) -> common.SignBlobResponse: 

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

929 private key. 

930 

931 .. code-block:: python 

932 

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

934 # code template only. 

935 # It will require modifications to work: 

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

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

938 # client as shown in: 

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

940 from google.cloud import iam_credentials_v1 

941 

942 def sample_sign_blob(): 

943 # Create a client 

944 client = iam_credentials_v1.IAMCredentialsClient() 

945 

946 # Initialize request argument(s) 

947 request = iam_credentials_v1.SignBlobRequest( 

948 name="name_value", 

949 payload=b'payload_blob', 

950 ) 

951 

952 # Make the request 

953 response = client.sign_blob(request=request) 

954 

955 # Handle the response 

956 print(response) 

957 

958 Args: 

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

960 The request object. 

961 name (str): 

962 Required. The resource name of the service account for 

963 which the credentials are requested, in the following 

964 format: 

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

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

967 with a project ID is invalid. 

968 

969 This corresponds to the ``name`` field 

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

971 should not be set. 

972 delegates (MutableSequence[str]): 

973 The sequence of service accounts in a delegation chain. 

974 Each service account must be granted the 

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

976 next service account in the chain. The last service 

977 account in the chain must be granted the 

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

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

980 of the request. 

981 

982 The delegates must have the following format: 

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

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

985 with a project ID is invalid. 

986 

987 This corresponds to the ``delegates`` field 

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

989 should not be set. 

990 payload (bytes): 

991 Required. The bytes to sign. 

992 This corresponds to the ``payload`` field 

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

994 should not be set. 

995 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

996 should be retried. 

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

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

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

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

1001 be of type `bytes`. 

1002 

1003 Returns: 

1004 google.cloud.iam_credentials_v1.types.SignBlobResponse: 

1005 

1006 """ 

1007 # Create or coerce a protobuf request object. 

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

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

1010 flattened_params = [name, delegates, payload] 

1011 has_flattened_params = ( 

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

1013 ) 

1014 if request is not None and has_flattened_params: 

1015 raise ValueError( 

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

1017 "the individual field arguments should be set." 

1018 ) 

1019 

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

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

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

1023 request = common.SignBlobRequest(request) 

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

1025 # request, apply these. 

1026 if name is not None: 

1027 request.name = name 

1028 if delegates is not None: 

1029 request.delegates = delegates 

1030 if payload is not None: 

1031 request.payload = payload 

1032 

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

1034 # and friendly error handling. 

1035 rpc = self._transport._wrapped_methods[self._transport.sign_blob] 

1036 

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

1038 # add these here. 

1039 metadata = tuple(metadata) + ( 

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

1041 ) 

1042 

1043 # Validate the universe domain. 

1044 self._validate_universe_domain() 

1045 

1046 # Send the request. 

1047 response = rpc( 

1048 request, 

1049 retry=retry, 

1050 timeout=timeout, 

1051 metadata=metadata, 

1052 ) 

1053 

1054 # Done; return the response. 

1055 return response 

1056 

1057 def sign_jwt( 

1058 self, 

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

1060 *, 

1061 name: Optional[str] = None, 

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

1063 payload: Optional[str] = None, 

1064 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1067 ) -> common.SignJwtResponse: 

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

1069 private key. 

1070 

1071 .. code-block:: python 

1072 

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

1074 # code template only. 

1075 # It will require modifications to work: 

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

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

1078 # client as shown in: 

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

1080 from google.cloud import iam_credentials_v1 

1081 

1082 def sample_sign_jwt(): 

1083 # Create a client 

1084 client = iam_credentials_v1.IAMCredentialsClient() 

1085 

1086 # Initialize request argument(s) 

1087 request = iam_credentials_v1.SignJwtRequest( 

1088 name="name_value", 

1089 payload="payload_value", 

1090 ) 

1091 

1092 # Make the request 

1093 response = client.sign_jwt(request=request) 

1094 

1095 # Handle the response 

1096 print(response) 

1097 

1098 Args: 

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

1100 The request object. 

1101 name (str): 

1102 Required. The resource name of the service account for 

1103 which the credentials are requested, in the following 

1104 format: 

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

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

1107 with a project ID is invalid. 

1108 

1109 This corresponds to the ``name`` field 

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

1111 should not be set. 

1112 delegates (MutableSequence[str]): 

1113 The sequence of service accounts in a delegation chain. 

1114 Each service account must be granted the 

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

1116 next service account in the chain. The last service 

1117 account in the chain must be granted the 

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

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

1120 of the request. 

1121 

1122 The delegates must have the following format: 

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

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

1125 with a project ID is invalid. 

1126 

1127 This corresponds to the ``delegates`` field 

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

1129 should not be set. 

1130 payload (str): 

1131 Required. The JWT payload to sign: a 

1132 JSON object that contains a JWT Claims 

1133 Set. 

1134 

1135 This corresponds to the ``payload`` field 

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

1137 should not be set. 

1138 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1139 should be retried. 

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

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

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

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

1144 be of type `bytes`. 

1145 

1146 Returns: 

1147 google.cloud.iam_credentials_v1.types.SignJwtResponse: 

1148 

1149 """ 

1150 # Create or coerce a protobuf request object. 

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

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

1153 flattened_params = [name, delegates, payload] 

1154 has_flattened_params = ( 

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

1156 ) 

1157 if request is not None and has_flattened_params: 

1158 raise ValueError( 

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

1160 "the individual field arguments should be set." 

1161 ) 

1162 

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

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

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

1166 request = common.SignJwtRequest(request) 

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

1168 # request, apply these. 

1169 if name is not None: 

1170 request.name = name 

1171 if delegates is not None: 

1172 request.delegates = delegates 

1173 if payload is not None: 

1174 request.payload = payload 

1175 

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

1177 # and friendly error handling. 

1178 rpc = self._transport._wrapped_methods[self._transport.sign_jwt] 

1179 

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

1181 # add these here. 

1182 metadata = tuple(metadata) + ( 

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

1184 ) 

1185 

1186 # Validate the universe domain. 

1187 self._validate_universe_domain() 

1188 

1189 # Send the request. 

1190 response = rpc( 

1191 request, 

1192 retry=retry, 

1193 timeout=timeout, 

1194 metadata=metadata, 

1195 ) 

1196 

1197 # Done; return the response. 

1198 return response 

1199 

1200 def __enter__(self) -> "IAMCredentialsClient": 

1201 return self 

1202 

1203 def __exit__(self, type, value, traceback): 

1204 """Releases underlying transport's resources. 

1205 

1206 .. warning:: 

1207 ONLY use as a context manager if the transport is NOT shared 

1208 with other clients! Exiting the with block will CLOSE the transport 

1209 and may cause errors in other clients! 

1210 """ 

1211 self.transport.close() 

1212 

1213 

1214DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1215 gapic_version=package_version.__version__ 

1216) 

1217DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1218 

1219__all__ = ("IAMCredentialsClient",)