Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.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

181 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 dataclasses 

17import json # type: ignore 

18import logging 

19import warnings 

20from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union 

21 

22import google.protobuf 

23from google.api_core import exceptions as core_exceptions 

24from google.api_core import gapic_v1, rest_helpers, rest_streaming 

25from google.api_core import retry as retries 

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

27from google.auth.transport.requests import AuthorizedSession # type: ignore 

28from google.protobuf import json_format 

29from requests import __version__ as requests_version 

30 

31from google.cloud.iam_credentials_v1._compat import transcode_request 

32from google.cloud.iam_credentials_v1.types import common 

33 

34from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO 

35from .rest_base import _BaseIAMCredentialsRestTransport 

36 

37try: 

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

39except AttributeError: # pragma: NO COVER 

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

41 

42try: 

43 from google.api_core import client_logging # type: ignore 

44 

45 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

46except ImportError: # pragma: NO COVER 

47 CLIENT_LOGGING_SUPPORTED = False 

48 

49_LOGGER = logging.getLogger(__name__) 

50 

51DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

52 gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, 

53 grpc_version=None, 

54 rest_version=f"requests@{requests_version}", 

55) 

56 

57DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

58 

59 

60class IAMCredentialsRestInterceptor: 

61 """Interceptor for IAMCredentials. 

62 

63 Interceptors are used to manipulate requests, request metadata, and responses 

64 in arbitrary ways. 

65 Example use cases include: 

66 * Logging 

67 * Verifying requests according to service or custom semantics 

68 * Stripping extraneous information from responses 

69 

70 These use cases and more can be enabled by injecting an 

71 instance of a custom subclass when constructing the IAMCredentialsRestTransport. 

72 

73 .. code-block:: python 

74 class MyCustomIAMCredentialsInterceptor(IAMCredentialsRestInterceptor): 

75 def pre_generate_access_token(self, request, metadata): 

76 logging.log(f"Received request: {request}") 

77 return request, metadata 

78 

79 def post_generate_access_token(self, response): 

80 logging.log(f"Received response: {response}") 

81 return response 

82 

83 def pre_generate_id_token(self, request, metadata): 

84 logging.log(f"Received request: {request}") 

85 return request, metadata 

86 

87 def post_generate_id_token(self, response): 

88 logging.log(f"Received response: {response}") 

89 return response 

90 

91 def pre_sign_blob(self, request, metadata): 

92 logging.log(f"Received request: {request}") 

93 return request, metadata 

94 

95 def post_sign_blob(self, response): 

96 logging.log(f"Received response: {response}") 

97 return response 

98 

99 def pre_sign_jwt(self, request, metadata): 

100 logging.log(f"Received request: {request}") 

101 return request, metadata 

102 

103 def post_sign_jwt(self, response): 

104 logging.log(f"Received response: {response}") 

105 return response 

106 

107 transport = IAMCredentialsRestTransport(interceptor=MyCustomIAMCredentialsInterceptor()) 

108 client = IAMCredentialsClient(transport=transport) 

109 

110 

111 """ 

112 

113 def pre_generate_access_token( 

114 self, 

115 request: common.GenerateAccessTokenRequest, 

116 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

117 ) -> Tuple[ 

118 common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] 

119 ]: 

120 """Pre-rpc interceptor for generate_access_token 

121 

122 Override in a subclass to manipulate the request or metadata 

123 before they are sent to the IAMCredentials server. 

124 """ 

125 return request, metadata 

126 

127 def post_generate_access_token( 

128 self, response: common.GenerateAccessTokenResponse 

129 ) -> common.GenerateAccessTokenResponse: 

130 """Post-rpc interceptor for generate_access_token 

131 

132 DEPRECATED. Please use the `post_generate_access_token_with_metadata` 

133 interceptor instead. 

134 

135 Override in a subclass to read or manipulate the response 

136 after it is returned by the IAMCredentials server but before 

137 it is returned to user code. This `post_generate_access_token` interceptor runs 

138 before the `post_generate_access_token_with_metadata` interceptor. 

139 """ 

140 return response 

141 

142 def post_generate_access_token_with_metadata( 

143 self, 

144 response: common.GenerateAccessTokenResponse, 

145 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

146 ) -> Tuple[ 

147 common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]] 

148 ]: 

149 """Post-rpc interceptor for generate_access_token 

150 

151 Override in a subclass to read or manipulate the response or metadata after it 

152 is returned by the IAMCredentials server but before it is returned to user code. 

153 

154 We recommend only using this `post_generate_access_token_with_metadata` 

155 interceptor in new development instead of the `post_generate_access_token` interceptor. 

156 When both interceptors are used, this `post_generate_access_token_with_metadata` interceptor runs after the 

157 `post_generate_access_token` interceptor. The (possibly modified) response returned by 

158 `post_generate_access_token` will be passed to 

159 `post_generate_access_token_with_metadata`. 

160 """ 

161 return response, metadata 

162 

163 def pre_generate_id_token( 

164 self, 

165 request: common.GenerateIdTokenRequest, 

166 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

167 ) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: 

168 """Pre-rpc interceptor for generate_id_token 

169 

170 Override in a subclass to manipulate the request or metadata 

171 before they are sent to the IAMCredentials server. 

172 """ 

173 return request, metadata 

174 

175 def post_generate_id_token( 

176 self, response: common.GenerateIdTokenResponse 

177 ) -> common.GenerateIdTokenResponse: 

178 """Post-rpc interceptor for generate_id_token 

179 

180 DEPRECATED. Please use the `post_generate_id_token_with_metadata` 

181 interceptor instead. 

182 

183 Override in a subclass to read or manipulate the response 

184 after it is returned by the IAMCredentials server but before 

185 it is returned to user code. This `post_generate_id_token` interceptor runs 

186 before the `post_generate_id_token_with_metadata` interceptor. 

187 """ 

188 return response 

189 

190 def post_generate_id_token_with_metadata( 

191 self, 

192 response: common.GenerateIdTokenResponse, 

193 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

194 ) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: 

195 """Post-rpc interceptor for generate_id_token 

196 

197 Override in a subclass to read or manipulate the response or metadata after it 

198 is returned by the IAMCredentials server but before it is returned to user code. 

199 

200 We recommend only using this `post_generate_id_token_with_metadata` 

201 interceptor in new development instead of the `post_generate_id_token` interceptor. 

202 When both interceptors are used, this `post_generate_id_token_with_metadata` interceptor runs after the 

203 `post_generate_id_token` interceptor. The (possibly modified) response returned by 

204 `post_generate_id_token` will be passed to 

205 `post_generate_id_token_with_metadata`. 

206 """ 

207 return response, metadata 

208 

209 def pre_sign_blob( 

210 self, 

211 request: common.SignBlobRequest, 

212 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

213 ) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: 

214 """Pre-rpc interceptor for sign_blob 

215 

216 Override in a subclass to manipulate the request or metadata 

217 before they are sent to the IAMCredentials server. 

218 """ 

219 return request, metadata 

220 

221 def post_sign_blob( 

222 self, response: common.SignBlobResponse 

223 ) -> common.SignBlobResponse: 

224 """Post-rpc interceptor for sign_blob 

225 

226 DEPRECATED. Please use the `post_sign_blob_with_metadata` 

227 interceptor instead. 

228 

229 Override in a subclass to read or manipulate the response 

230 after it is returned by the IAMCredentials server but before 

231 it is returned to user code. This `post_sign_blob` interceptor runs 

232 before the `post_sign_blob_with_metadata` interceptor. 

233 """ 

234 return response 

235 

236 def post_sign_blob_with_metadata( 

237 self, 

238 response: common.SignBlobResponse, 

239 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

240 ) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: 

241 """Post-rpc interceptor for sign_blob 

242 

243 Override in a subclass to read or manipulate the response or metadata after it 

244 is returned by the IAMCredentials server but before it is returned to user code. 

245 

246 We recommend only using this `post_sign_blob_with_metadata` 

247 interceptor in new development instead of the `post_sign_blob` interceptor. 

248 When both interceptors are used, this `post_sign_blob_with_metadata` interceptor runs after the 

249 `post_sign_blob` interceptor. The (possibly modified) response returned by 

250 `post_sign_blob` will be passed to 

251 `post_sign_blob_with_metadata`. 

252 """ 

253 return response, metadata 

254 

255 def pre_sign_jwt( 

256 self, 

257 request: common.SignJwtRequest, 

258 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

259 ) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: 

260 """Pre-rpc interceptor for sign_jwt 

261 

262 Override in a subclass to manipulate the request or metadata 

263 before they are sent to the IAMCredentials server. 

264 """ 

265 return request, metadata 

266 

267 def post_sign_jwt(self, response: common.SignJwtResponse) -> common.SignJwtResponse: 

268 """Post-rpc interceptor for sign_jwt 

269 

270 DEPRECATED. Please use the `post_sign_jwt_with_metadata` 

271 interceptor instead. 

272 

273 Override in a subclass to read or manipulate the response 

274 after it is returned by the IAMCredentials server but before 

275 it is returned to user code. This `post_sign_jwt` interceptor runs 

276 before the `post_sign_jwt_with_metadata` interceptor. 

277 """ 

278 return response 

279 

280 def post_sign_jwt_with_metadata( 

281 self, 

282 response: common.SignJwtResponse, 

283 metadata: Sequence[Tuple[str, Union[str, bytes]]], 

284 ) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: 

285 """Post-rpc interceptor for sign_jwt 

286 

287 Override in a subclass to read or manipulate the response or metadata after it 

288 is returned by the IAMCredentials server but before it is returned to user code. 

289 

290 We recommend only using this `post_sign_jwt_with_metadata` 

291 interceptor in new development instead of the `post_sign_jwt` interceptor. 

292 When both interceptors are used, this `post_sign_jwt_with_metadata` interceptor runs after the 

293 `post_sign_jwt` interceptor. The (possibly modified) response returned by 

294 `post_sign_jwt` will be passed to 

295 `post_sign_jwt_with_metadata`. 

296 """ 

297 return response, metadata 

298 

299 

300@dataclasses.dataclass 

301class IAMCredentialsRestStub: 

302 _session: AuthorizedSession 

303 _host: str 

304 _interceptor: IAMCredentialsRestInterceptor 

305 

306 

307class IAMCredentialsRestTransport(_BaseIAMCredentialsRestTransport): 

308 """REST backend synchronous transport for IAMCredentials. 

309 

310 A service account is a special type of Google account that 

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

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

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

314 users aren't directly involved. 

315 

316 Service account credentials are used to temporarily assume the 

317 identity of the service account. Supported credential types 

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

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

320 

321 This class defines the same methods as the primary client, so the 

322 primary client can load the underlying transport implementation 

323 and call it. 

324 

325 It sends JSON representations of protocol buffers over HTTP/1.1 

326 """ 

327 

328 def __init__( 

329 self, 

330 *, 

331 host: str = "iamcredentials.googleapis.com", 

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

333 credentials_file: Optional[str] = None, 

334 scopes: Optional[Sequence[str]] = None, 

335 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

336 quota_project_id: Optional[str] = None, 

337 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

338 always_use_jwt_access: Optional[bool] = False, 

339 url_scheme: str = "https", 

340 interceptor: Optional[IAMCredentialsRestInterceptor] = None, 

341 api_audience: Optional[str] = None, 

342 ) -> None: 

343 """Instantiate the transport. 

344 

345 Args: 

346 host (Optional[str]): 

347 The hostname to connect to (default: 'iamcredentials.googleapis.com'). 

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

349 authorization credentials to attach to requests. These 

350 credentials identify the application to the service; if none 

351 are specified, the client will attempt to ascertain the 

352 credentials from the environment. 

353 

354 credentials_file (Optional[str]): Deprecated. A file with credentials that can 

355 be loaded with :func:`google.auth.load_credentials_from_file`. 

356 This argument is ignored if ``channel`` is provided. This argument will be 

357 removed in the next major version of this library. 

358 scopes (Optional(Sequence[str])): A list of scopes. This argument is 

359 ignored if ``channel`` is provided. 

360 client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client 

361 certificate to configure mutual TLS HTTP channel. It is ignored 

362 if ``channel`` is provided. 

363 quota_project_id (Optional[str]): An optional project to use for billing 

364 and quota. 

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

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

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

368 Generally, you only need to set this if you are developing 

369 your own client library. 

370 always_use_jwt_access (Optional[bool]): Whether self signed JWT should 

371 be used for service account credentials. 

372 url_scheme: the protocol scheme for the API endpoint. Normally 

373 "https", but for testing or local servers, 

374 "http" can be specified. 

375 interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used 

376 to manipulate requests, request metadata, and responses. 

377 api_audience (Optional[str]): The intended audience for the API calls 

378 to the service that will be set when using certain 3rd party 

379 authentication flows. Audience is typically a resource identifier. 

380 If not set, the host value will be used as a default. 

381 """ 

382 # Run the base constructor 

383 # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. 

384 # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the 

385 # credentials object 

386 super().__init__( 

387 host=host, 

388 credentials=credentials, 

389 client_info=client_info, 

390 always_use_jwt_access=always_use_jwt_access, 

391 url_scheme=url_scheme, 

392 api_audience=api_audience, 

393 ) 

394 self._session = AuthorizedSession( 

395 self._credentials, default_host=self.DEFAULT_HOST 

396 ) 

397 if client_cert_source_for_mtls: 

398 self._session.configure_mtls_channel(client_cert_source_for_mtls) 

399 self._interceptor = interceptor or IAMCredentialsRestInterceptor() 

400 self._prep_wrapped_messages(client_info) 

401 

402 class _GenerateAccessToken( 

403 _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, 

404 IAMCredentialsRestStub, 

405 ): 

406 def __hash__(self): 

407 return hash("IAMCredentialsRestTransport.GenerateAccessToken") 

408 

409 @staticmethod 

410 def _get_response( 

411 host, 

412 metadata, 

413 query_params, 

414 session, 

415 timeout, 

416 transcoded_request, 

417 body=None, 

418 ): 

419 uri = transcoded_request["uri"] 

420 method = transcoded_request["method"] 

421 headers = dict(metadata) 

422 headers["Content-Type"] = "application/json" 

423 response = getattr(session, method)( 

424 "{host}{uri}".format(host=host, uri=uri), 

425 timeout=timeout, 

426 headers=headers, 

427 params=rest_helpers.flatten_query_params(query_params, strict=True), 

428 data=body, 

429 ) 

430 return response 

431 

432 def __call__( 

433 self, 

434 request: common.GenerateAccessTokenRequest, 

435 *, 

436 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

437 timeout: Optional[float] = None, 

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

439 ) -> common.GenerateAccessTokenResponse: 

440 r"""Call the generate access token method over HTTP. 

441 

442 Args: 

443 request (~.common.GenerateAccessTokenRequest): 

444 The request object. 

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

446 should be retried. 

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

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

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

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

451 be of type `bytes`. 

452 

453 Returns: 

454 ~.common.GenerateAccessTokenResponse: 

455 

456 """ 

457 

458 http_options = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_http_options() 

459 request, metadata = self._interceptor.pre_generate_access_token( 

460 request, metadata 

461 ) 

462 transcoded_request, body, query_params = transcode_request( 

463 http_options, 

464 request, 

465 required_fields_default_values=getattr( 

466 _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, 

467 "_BaseGenerateAccessToken__REQUIRED_FIELDS_DEFAULT_VALUES", 

468 None, 

469 ), 

470 rest_numeric_enums=True, 

471 ) 

472 

473 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

474 logging.DEBUG 

475 ): # pragma: NO COVER 

476 request_url = "{host}{uri}".format( 

477 host=self._host, uri=transcoded_request["uri"] 

478 ) 

479 method = transcoded_request["method"] 

480 try: 

481 request_payload = type(request).to_json(request) 

482 except: 

483 request_payload = None 

484 http_request = { 

485 "payload": request_payload, 

486 "requestMethod": method, 

487 "requestUrl": request_url, 

488 "headers": dict(metadata), 

489 } 

490 _LOGGER.debug( 

491 f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateAccessToken", 

492 extra={ 

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

494 "rpcName": "GenerateAccessToken", 

495 "httpRequest": http_request, 

496 "metadata": http_request["headers"], 

497 }, 

498 ) 

499 

500 # Send the request 

501 response = IAMCredentialsRestTransport._GenerateAccessToken._get_response( 

502 self._host, 

503 metadata, 

504 query_params, 

505 self._session, 

506 timeout, 

507 transcoded_request, 

508 body, 

509 ) 

510 

511 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception 

512 # subclass. 

513 if response.status_code >= 400: 

514 raise core_exceptions.from_http_response(response) 

515 

516 # Return the response 

517 resp = common.GenerateAccessTokenResponse() 

518 pb_resp = common.GenerateAccessTokenResponse.pb(resp) 

519 

520 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) 

521 

522 resp = self._interceptor.post_generate_access_token(resp) 

523 response_metadata = [(k, str(v)) for k, v in response.headers.items()] 

524 resp, _ = self._interceptor.post_generate_access_token_with_metadata( 

525 resp, response_metadata 

526 ) 

527 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

528 logging.DEBUG 

529 ): # pragma: NO COVER 

530 try: 

531 response_payload = common.GenerateAccessTokenResponse.to_json( 

532 response 

533 ) 

534 except: 

535 response_payload = None 

536 http_response = { 

537 "payload": response_payload, 

538 "headers": dict(response.headers), 

539 "status": response.status_code, 

540 } 

541 _LOGGER.debug( 

542 "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_access_token", 

543 extra={ 

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

545 "rpcName": "GenerateAccessToken", 

546 "metadata": http_response["headers"], 

547 "httpResponse": http_response, 

548 }, 

549 ) 

550 return resp 

551 

552 class _GenerateIdToken( 

553 _BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub 

554 ): 

555 def __hash__(self): 

556 return hash("IAMCredentialsRestTransport.GenerateIdToken") 

557 

558 @staticmethod 

559 def _get_response( 

560 host, 

561 metadata, 

562 query_params, 

563 session, 

564 timeout, 

565 transcoded_request, 

566 body=None, 

567 ): 

568 uri = transcoded_request["uri"] 

569 method = transcoded_request["method"] 

570 headers = dict(metadata) 

571 headers["Content-Type"] = "application/json" 

572 response = getattr(session, method)( 

573 "{host}{uri}".format(host=host, uri=uri), 

574 timeout=timeout, 

575 headers=headers, 

576 params=rest_helpers.flatten_query_params(query_params, strict=True), 

577 data=body, 

578 ) 

579 return response 

580 

581 def __call__( 

582 self, 

583 request: common.GenerateIdTokenRequest, 

584 *, 

585 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

586 timeout: Optional[float] = None, 

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

588 ) -> common.GenerateIdTokenResponse: 

589 r"""Call the generate id token method over HTTP. 

590 

591 Args: 

592 request (~.common.GenerateIdTokenRequest): 

593 The request object. 

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

595 should be retried. 

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

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

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

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

600 be of type `bytes`. 

601 

602 Returns: 

603 ~.common.GenerateIdTokenResponse: 

604 

605 """ 

606 

607 http_options = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_http_options() 

608 request, metadata = self._interceptor.pre_generate_id_token( 

609 request, metadata 

610 ) 

611 transcoded_request, body, query_params = transcode_request( 

612 http_options, 

613 request, 

614 required_fields_default_values=getattr( 

615 _BaseIAMCredentialsRestTransport._BaseGenerateIdToken, 

616 "_BaseGenerateIdToken__REQUIRED_FIELDS_DEFAULT_VALUES", 

617 None, 

618 ), 

619 rest_numeric_enums=True, 

620 ) 

621 

622 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

623 logging.DEBUG 

624 ): # pragma: NO COVER 

625 request_url = "{host}{uri}".format( 

626 host=self._host, uri=transcoded_request["uri"] 

627 ) 

628 method = transcoded_request["method"] 

629 try: 

630 request_payload = type(request).to_json(request) 

631 except: 

632 request_payload = None 

633 http_request = { 

634 "payload": request_payload, 

635 "requestMethod": method, 

636 "requestUrl": request_url, 

637 "headers": dict(metadata), 

638 } 

639 _LOGGER.debug( 

640 f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateIdToken", 

641 extra={ 

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

643 "rpcName": "GenerateIdToken", 

644 "httpRequest": http_request, 

645 "metadata": http_request["headers"], 

646 }, 

647 ) 

648 

649 # Send the request 

650 response = IAMCredentialsRestTransport._GenerateIdToken._get_response( 

651 self._host, 

652 metadata, 

653 query_params, 

654 self._session, 

655 timeout, 

656 transcoded_request, 

657 body, 

658 ) 

659 

660 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception 

661 # subclass. 

662 if response.status_code >= 400: 

663 raise core_exceptions.from_http_response(response) 

664 

665 # Return the response 

666 resp = common.GenerateIdTokenResponse() 

667 pb_resp = common.GenerateIdTokenResponse.pb(resp) 

668 

669 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) 

670 

671 resp = self._interceptor.post_generate_id_token(resp) 

672 response_metadata = [(k, str(v)) for k, v in response.headers.items()] 

673 resp, _ = self._interceptor.post_generate_id_token_with_metadata( 

674 resp, response_metadata 

675 ) 

676 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

677 logging.DEBUG 

678 ): # pragma: NO COVER 

679 try: 

680 response_payload = common.GenerateIdTokenResponse.to_json(response) 

681 except: 

682 response_payload = None 

683 http_response = { 

684 "payload": response_payload, 

685 "headers": dict(response.headers), 

686 "status": response.status_code, 

687 } 

688 _LOGGER.debug( 

689 "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_id_token", 

690 extra={ 

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

692 "rpcName": "GenerateIdToken", 

693 "metadata": http_response["headers"], 

694 "httpResponse": http_response, 

695 }, 

696 ) 

697 return resp 

698 

699 class _SignBlob( 

700 _BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub 

701 ): 

702 def __hash__(self): 

703 return hash("IAMCredentialsRestTransport.SignBlob") 

704 

705 @staticmethod 

706 def _get_response( 

707 host, 

708 metadata, 

709 query_params, 

710 session, 

711 timeout, 

712 transcoded_request, 

713 body=None, 

714 ): 

715 uri = transcoded_request["uri"] 

716 method = transcoded_request["method"] 

717 headers = dict(metadata) 

718 headers["Content-Type"] = "application/json" 

719 response = getattr(session, method)( 

720 "{host}{uri}".format(host=host, uri=uri), 

721 timeout=timeout, 

722 headers=headers, 

723 params=rest_helpers.flatten_query_params(query_params, strict=True), 

724 data=body, 

725 ) 

726 return response 

727 

728 def __call__( 

729 self, 

730 request: common.SignBlobRequest, 

731 *, 

732 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

733 timeout: Optional[float] = None, 

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

735 ) -> common.SignBlobResponse: 

736 r"""Call the sign blob method over HTTP. 

737 

738 Args: 

739 request (~.common.SignBlobRequest): 

740 The request object. 

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

742 should be retried. 

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

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

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

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

747 be of type `bytes`. 

748 

749 Returns: 

750 ~.common.SignBlobResponse: 

751 

752 """ 

753 

754 http_options = ( 

755 _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() 

756 ) 

757 request, metadata = self._interceptor.pre_sign_blob(request, metadata) 

758 transcoded_request, body, query_params = transcode_request( 

759 http_options, 

760 request, 

761 required_fields_default_values=getattr( 

762 _BaseIAMCredentialsRestTransport._BaseSignBlob, 

763 "_BaseSignBlob__REQUIRED_FIELDS_DEFAULT_VALUES", 

764 None, 

765 ), 

766 rest_numeric_enums=True, 

767 ) 

768 

769 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

770 logging.DEBUG 

771 ): # pragma: NO COVER 

772 request_url = "{host}{uri}".format( 

773 host=self._host, uri=transcoded_request["uri"] 

774 ) 

775 method = transcoded_request["method"] 

776 try: 

777 request_payload = type(request).to_json(request) 

778 except: 

779 request_payload = None 

780 http_request = { 

781 "payload": request_payload, 

782 "requestMethod": method, 

783 "requestUrl": request_url, 

784 "headers": dict(metadata), 

785 } 

786 _LOGGER.debug( 

787 f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignBlob", 

788 extra={ 

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

790 "rpcName": "SignBlob", 

791 "httpRequest": http_request, 

792 "metadata": http_request["headers"], 

793 }, 

794 ) 

795 

796 # Send the request 

797 response = IAMCredentialsRestTransport._SignBlob._get_response( 

798 self._host, 

799 metadata, 

800 query_params, 

801 self._session, 

802 timeout, 

803 transcoded_request, 

804 body, 

805 ) 

806 

807 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception 

808 # subclass. 

809 if response.status_code >= 400: 

810 raise core_exceptions.from_http_response(response) 

811 

812 # Return the response 

813 resp = common.SignBlobResponse() 

814 pb_resp = common.SignBlobResponse.pb(resp) 

815 

816 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) 

817 

818 resp = self._interceptor.post_sign_blob(resp) 

819 response_metadata = [(k, str(v)) for k, v in response.headers.items()] 

820 resp, _ = self._interceptor.post_sign_blob_with_metadata( 

821 resp, response_metadata 

822 ) 

823 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

824 logging.DEBUG 

825 ): # pragma: NO COVER 

826 try: 

827 response_payload = common.SignBlobResponse.to_json(response) 

828 except: 

829 response_payload = None 

830 http_response = { 

831 "payload": response_payload, 

832 "headers": dict(response.headers), 

833 "status": response.status_code, 

834 } 

835 _LOGGER.debug( 

836 "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_blob", 

837 extra={ 

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

839 "rpcName": "SignBlob", 

840 "metadata": http_response["headers"], 

841 "httpResponse": http_response, 

842 }, 

843 ) 

844 return resp 

845 

846 class _SignJwt( 

847 _BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub 

848 ): 

849 def __hash__(self): 

850 return hash("IAMCredentialsRestTransport.SignJwt") 

851 

852 @staticmethod 

853 def _get_response( 

854 host, 

855 metadata, 

856 query_params, 

857 session, 

858 timeout, 

859 transcoded_request, 

860 body=None, 

861 ): 

862 uri = transcoded_request["uri"] 

863 method = transcoded_request["method"] 

864 headers = dict(metadata) 

865 headers["Content-Type"] = "application/json" 

866 response = getattr(session, method)( 

867 "{host}{uri}".format(host=host, uri=uri), 

868 timeout=timeout, 

869 headers=headers, 

870 params=rest_helpers.flatten_query_params(query_params, strict=True), 

871 data=body, 

872 ) 

873 return response 

874 

875 def __call__( 

876 self, 

877 request: common.SignJwtRequest, 

878 *, 

879 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

880 timeout: Optional[float] = None, 

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

882 ) -> common.SignJwtResponse: 

883 r"""Call the sign jwt method over HTTP. 

884 

885 Args: 

886 request (~.common.SignJwtRequest): 

887 The request object. 

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

889 should be retried. 

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

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

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

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

894 be of type `bytes`. 

895 

896 Returns: 

897 ~.common.SignJwtResponse: 

898 

899 """ 

900 

901 http_options = ( 

902 _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() 

903 ) 

904 request, metadata = self._interceptor.pre_sign_jwt(request, metadata) 

905 transcoded_request, body, query_params = transcode_request( 

906 http_options, 

907 request, 

908 required_fields_default_values=getattr( 

909 _BaseIAMCredentialsRestTransport._BaseSignJwt, 

910 "_BaseSignJwt__REQUIRED_FIELDS_DEFAULT_VALUES", 

911 None, 

912 ), 

913 rest_numeric_enums=True, 

914 ) 

915 

916 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

917 logging.DEBUG 

918 ): # pragma: NO COVER 

919 request_url = "{host}{uri}".format( 

920 host=self._host, uri=transcoded_request["uri"] 

921 ) 

922 method = transcoded_request["method"] 

923 try: 

924 request_payload = type(request).to_json(request) 

925 except: 

926 request_payload = None 

927 http_request = { 

928 "payload": request_payload, 

929 "requestMethod": method, 

930 "requestUrl": request_url, 

931 "headers": dict(metadata), 

932 } 

933 _LOGGER.debug( 

934 f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignJwt", 

935 extra={ 

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

937 "rpcName": "SignJwt", 

938 "httpRequest": http_request, 

939 "metadata": http_request["headers"], 

940 }, 

941 ) 

942 

943 # Send the request 

944 response = IAMCredentialsRestTransport._SignJwt._get_response( 

945 self._host, 

946 metadata, 

947 query_params, 

948 self._session, 

949 timeout, 

950 transcoded_request, 

951 body, 

952 ) 

953 

954 # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception 

955 # subclass. 

956 if response.status_code >= 400: 

957 raise core_exceptions.from_http_response(response) 

958 

959 # Return the response 

960 resp = common.SignJwtResponse() 

961 pb_resp = common.SignJwtResponse.pb(resp) 

962 

963 json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) 

964 

965 resp = self._interceptor.post_sign_jwt(resp) 

966 response_metadata = [(k, str(v)) for k, v in response.headers.items()] 

967 resp, _ = self._interceptor.post_sign_jwt_with_metadata( 

968 resp, response_metadata 

969 ) 

970 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

971 logging.DEBUG 

972 ): # pragma: NO COVER 

973 try: 

974 response_payload = common.SignJwtResponse.to_json(response) 

975 except: 

976 response_payload = None 

977 http_response = { 

978 "payload": response_payload, 

979 "headers": dict(response.headers), 

980 "status": response.status_code, 

981 } 

982 _LOGGER.debug( 

983 "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_jwt", 

984 extra={ 

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

986 "rpcName": "SignJwt", 

987 "metadata": http_response["headers"], 

988 "httpResponse": http_response, 

989 }, 

990 ) 

991 return resp 

992 

993 @property 

994 def generate_access_token( 

995 self, 

996 ) -> Callable[ 

997 [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse 

998 ]: 

999 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. 

1000 # In C++ this would require a dynamic_cast 

1001 return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore 

1002 

1003 @property 

1004 def generate_id_token( 

1005 self, 

1006 ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: 

1007 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. 

1008 # In C++ this would require a dynamic_cast 

1009 return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore 

1010 

1011 @property 

1012 def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: 

1013 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. 

1014 # In C++ this would require a dynamic_cast 

1015 return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore 

1016 

1017 @property 

1018 def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: 

1019 # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. 

1020 # In C++ this would require a dynamic_cast 

1021 return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore 

1022 

1023 @property 

1024 def kind(self) -> str: 

1025 return "rest" 

1026 

1027 def close(self): 

1028 self._session.close() 

1029 

1030 

1031__all__ = ("IAMCredentialsRestTransport",)