Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/auth/_default.py: 17%

222 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-08-16 06:17 +0000

1# Copyright 2015 Google Inc. 

2# 

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

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

5# You may obtain a copy of the License at 

6# 

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

8# 

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

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

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

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

13# limitations under the License. 

14 

15"""Application default credentials. 

16 

17Implements application default credentials and project ID detection. 

18""" 

19 

20import io 

21import json 

22import logging 

23import os 

24import warnings 

25 

26import six 

27 

28from google.auth import environment_vars 

29from google.auth import exceptions 

30import google.auth.transport._http_client 

31 

32_LOGGER = logging.getLogger(__name__) 

33 

34# Valid types accepted for file-based credentials. 

35_AUTHORIZED_USER_TYPE = "authorized_user" 

36_SERVICE_ACCOUNT_TYPE = "service_account" 

37_EXTERNAL_ACCOUNT_TYPE = "external_account" 

38_EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user" 

39_IMPERSONATED_SERVICE_ACCOUNT_TYPE = "impersonated_service_account" 

40_GDCH_SERVICE_ACCOUNT_TYPE = "gdch_service_account" 

41_VALID_TYPES = ( 

42 _AUTHORIZED_USER_TYPE, 

43 _SERVICE_ACCOUNT_TYPE, 

44 _EXTERNAL_ACCOUNT_TYPE, 

45 _EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE, 

46 _IMPERSONATED_SERVICE_ACCOUNT_TYPE, 

47 _GDCH_SERVICE_ACCOUNT_TYPE, 

48) 

49 

50# Help message when no credentials can be found. 

51_CLOUD_SDK_MISSING_CREDENTIALS = """\ 

52Your default credentials were not found. To set up Application Default Credentials, \ 

53see https://cloud.google.com/docs/authentication/external/set-up-adc for more information.\ 

54""" 

55 

56# Warning when using Cloud SDK user credentials 

57_CLOUD_SDK_CREDENTIALS_WARNING = """\ 

58Your application has authenticated using end user credentials from Google \ 

59Cloud SDK without a quota project. You might receive a "quota exceeded" \ 

60or "API not enabled" error. See the following page for troubleshooting: \ 

61https://cloud.google.com/docs/authentication/adc-troubleshooting/user-creds. \ 

62""" 

63 

64# The subject token type used for AWS external_account credentials. 

65_AWS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:aws:token-type:aws4_request" 

66 

67 

68def _warn_about_problematic_credentials(credentials): 

69 """Determines if the credentials are problematic. 

70 

71 Credentials from the Cloud SDK that are associated with Cloud SDK's project 

72 are problematic because they may not have APIs enabled and have limited 

73 quota. If this is the case, warn about it. 

74 """ 

75 from google.auth import _cloud_sdk 

76 

77 if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID: 

78 warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING) 

79 

80 

81def load_credentials_from_file( 

82 filename, scopes=None, default_scopes=None, quota_project_id=None, request=None 

83): 

84 """Loads Google credentials from a file. 

85 

86 The credentials file must be a service account key, stored authorized 

87 user credentials, external account credentials, or impersonated service 

88 account credentials. 

89 

90 Args: 

91 filename (str): The full path to the credentials file. 

92 scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If 

93 specified, the credentials will automatically be scoped if 

94 necessary 

95 default_scopes (Optional[Sequence[str]]): Default scopes passed by a 

96 Google client library. Use 'scopes' for user-defined scopes. 

97 quota_project_id (Optional[str]): The project ID used for 

98 quota and billing. 

99 request (Optional[google.auth.transport.Request]): An object used to make 

100 HTTP requests. This is used to determine the associated project ID 

101 for a workload identity pool resource (external account credentials). 

102 If not specified, then it will use a 

103 google.auth.transport.requests.Request client to make requests. 

104 

105 Returns: 

106 Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded 

107 credentials and the project ID. Authorized user credentials do not 

108 have the project ID information. External account credentials project 

109 IDs may not always be determined. 

110 

111 Raises: 

112 google.auth.exceptions.DefaultCredentialsError: if the file is in the 

113 wrong format or is missing. 

114 """ 

115 if not os.path.exists(filename): 

116 raise exceptions.DefaultCredentialsError( 

117 "File {} was not found.".format(filename) 

118 ) 

119 

120 with io.open(filename, "r") as file_obj: 

121 try: 

122 info = json.load(file_obj) 

123 except ValueError as caught_exc: 

124 new_exc = exceptions.DefaultCredentialsError( 

125 "File {} is not a valid json file.".format(filename), caught_exc 

126 ) 

127 six.raise_from(new_exc, caught_exc) 

128 return _load_credentials_from_info( 

129 filename, info, scopes, default_scopes, quota_project_id, request 

130 ) 

131 

132 

133def load_credentials_from_dict( 

134 info, scopes=None, default_scopes=None, quota_project_id=None, request=None 

135): 

136 """Loads Google credentials from a dict. 

137 

138 The credentials file must be a service account key, stored authorized 

139 user credentials, external account credentials, or impersonated service 

140 account credentials. 

141 

142 Args: 

143 info (Dict[str, Any]): A dict object containing the credentials 

144 scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If 

145 specified, the credentials will automatically be scoped if 

146 necessary 

147 default_scopes (Optional[Sequence[str]]): Default scopes passed by a 

148 Google client library. Use 'scopes' for user-defined scopes. 

149 quota_project_id (Optional[str]): The project ID used for 

150 quota and billing. 

151 request (Optional[google.auth.transport.Request]): An object used to make 

152 HTTP requests. This is used to determine the associated project ID 

153 for a workload identity pool resource (external account credentials). 

154 If not specified, then it will use a 

155 google.auth.transport.requests.Request client to make requests. 

156 

157 Returns: 

158 Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded 

159 credentials and the project ID. Authorized user credentials do not 

160 have the project ID information. External account credentials project 

161 IDs may not always be determined. 

162 

163 Raises: 

164 google.auth.exceptions.DefaultCredentialsError: if the file is in the 

165 wrong format or is missing. 

166 """ 

167 if not isinstance(info, dict): 

168 raise exceptions.DefaultCredentialsError( 

169 "info object was of type {} but dict type was expected.".format(type(info)) 

170 ) 

171 

172 return _load_credentials_from_info( 

173 "dict object", info, scopes, default_scopes, quota_project_id, request 

174 ) 

175 

176 

177def _load_credentials_from_info( 

178 filename, info, scopes, default_scopes, quota_project_id, request 

179): 

180 from google.auth.credentials import CredentialsWithQuotaProject 

181 

182 credential_type = info.get("type") 

183 

184 if credential_type == _AUTHORIZED_USER_TYPE: 

185 credentials, project_id = _get_authorized_user_credentials( 

186 filename, info, scopes 

187 ) 

188 

189 elif credential_type == _SERVICE_ACCOUNT_TYPE: 

190 credentials, project_id = _get_service_account_credentials( 

191 filename, info, scopes, default_scopes 

192 ) 

193 

194 elif credential_type == _EXTERNAL_ACCOUNT_TYPE: 

195 credentials, project_id = _get_external_account_credentials( 

196 info, 

197 filename, 

198 scopes=scopes, 

199 default_scopes=default_scopes, 

200 request=request, 

201 ) 

202 

203 elif credential_type == _EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE: 

204 credentials, project_id = _get_external_account_authorized_user_credentials( 

205 filename, info, request 

206 ) 

207 

208 elif credential_type == _IMPERSONATED_SERVICE_ACCOUNT_TYPE: 

209 credentials, project_id = _get_impersonated_service_account_credentials( 

210 filename, info, scopes 

211 ) 

212 elif credential_type == _GDCH_SERVICE_ACCOUNT_TYPE: 

213 credentials, project_id = _get_gdch_service_account_credentials(filename, info) 

214 else: 

215 raise exceptions.DefaultCredentialsError( 

216 "The file {file} does not have a valid type. " 

217 "Type is {type}, expected one of {valid_types}.".format( 

218 file=filename, type=credential_type, valid_types=_VALID_TYPES 

219 ) 

220 ) 

221 if isinstance(credentials, CredentialsWithQuotaProject): 

222 credentials = _apply_quota_project_id(credentials, quota_project_id) 

223 return credentials, project_id 

224 

225 

226def _get_gcloud_sdk_credentials(quota_project_id=None): 

227 """Gets the credentials and project ID from the Cloud SDK.""" 

228 from google.auth import _cloud_sdk 

229 

230 _LOGGER.debug("Checking Cloud SDK credentials as part of auth process...") 

231 

232 # Check if application default credentials exist. 

233 credentials_filename = _cloud_sdk.get_application_default_credentials_path() 

234 

235 if not os.path.isfile(credentials_filename): 

236 _LOGGER.debug("Cloud SDK credentials not found on disk; not using them") 

237 return None, None 

238 

239 credentials, project_id = load_credentials_from_file( 

240 credentials_filename, quota_project_id=quota_project_id 

241 ) 

242 

243 if not project_id: 

244 project_id = _cloud_sdk.get_project_id() 

245 

246 return credentials, project_id 

247 

248 

249def _get_explicit_environ_credentials(quota_project_id=None): 

250 """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment 

251 variable.""" 

252 from google.auth import _cloud_sdk 

253 

254 cloud_sdk_adc_path = _cloud_sdk.get_application_default_credentials_path() 

255 explicit_file = os.environ.get(environment_vars.CREDENTIALS) 

256 

257 _LOGGER.debug( 

258 "Checking %s for explicit credentials as part of auth process...", explicit_file 

259 ) 

260 

261 if explicit_file is not None and explicit_file == cloud_sdk_adc_path: 

262 # Cloud sdk flow calls gcloud to fetch project id, so if the explicit 

263 # file path is cloud sdk credentials path, then we should fall back 

264 # to cloud sdk flow, otherwise project id cannot be obtained. 

265 _LOGGER.debug( 

266 "Explicit credentials path %s is the same as Cloud SDK credentials path, fall back to Cloud SDK credentials flow...", 

267 explicit_file, 

268 ) 

269 return _get_gcloud_sdk_credentials(quota_project_id=quota_project_id) 

270 

271 if explicit_file is not None: 

272 credentials, project_id = load_credentials_from_file( 

273 os.environ[environment_vars.CREDENTIALS], quota_project_id=quota_project_id 

274 ) 

275 

276 return credentials, project_id 

277 

278 else: 

279 return None, None 

280 

281 

282def _get_gae_credentials(): 

283 """Gets Google App Engine App Identity credentials and project ID.""" 

284 # If not GAE gen1, prefer the metadata service even if the GAE APIs are 

285 # available as per https://google.aip.dev/auth/4115. 

286 if os.environ.get(environment_vars.LEGACY_APPENGINE_RUNTIME) != "python27": 

287 return None, None 

288 

289 # While this library is normally bundled with app_engine, there are 

290 # some cases where it's not available, so we tolerate ImportError. 

291 try: 

292 _LOGGER.debug("Checking for App Engine runtime as part of auth process...") 

293 import google.auth.app_engine as app_engine 

294 except ImportError: 

295 _LOGGER.warning("Import of App Engine auth library failed.") 

296 return None, None 

297 

298 try: 

299 credentials = app_engine.Credentials() 

300 project_id = app_engine.get_project_id() 

301 return credentials, project_id 

302 except EnvironmentError: 

303 _LOGGER.debug( 

304 "No App Engine library was found so cannot authentication via App Engine Identity Credentials." 

305 ) 

306 return None, None 

307 

308 

309def _get_gce_credentials(request=None, quota_project_id=None): 

310 """Gets credentials and project ID from the GCE Metadata Service.""" 

311 # Ping requires a transport, but we want application default credentials 

312 # to require no arguments. So, we'll use the _http_client transport which 

313 # uses http.client. This is only acceptable because the metadata server 

314 # doesn't do SSL and never requires proxies. 

315 

316 # While this library is normally bundled with compute_engine, there are 

317 # some cases where it's not available, so we tolerate ImportError. 

318 try: 

319 from google.auth import compute_engine 

320 from google.auth.compute_engine import _metadata 

321 except ImportError: 

322 _LOGGER.warning("Import of Compute Engine auth library failed.") 

323 return None, None 

324 

325 if request is None: 

326 request = google.auth.transport._http_client.Request() 

327 

328 if _metadata.is_on_gce(request=request): 

329 # Get the project ID. 

330 try: 

331 project_id = _metadata.get_project_id(request=request) 

332 except exceptions.TransportError: 

333 project_id = None 

334 

335 cred = compute_engine.Credentials() 

336 cred = _apply_quota_project_id(cred, quota_project_id) 

337 

338 return cred, project_id 

339 else: 

340 _LOGGER.warning( 

341 "Authentication failed using Compute Engine authentication due to unavailable metadata server." 

342 ) 

343 return None, None 

344 

345 

346def _get_external_account_credentials( 

347 info, filename, scopes=None, default_scopes=None, request=None 

348): 

349 """Loads external account Credentials from the parsed external account info. 

350 

351 The credentials information must correspond to a supported external account 

352 credentials. 

353 

354 Args: 

355 info (Mapping[str, str]): The external account info in Google format. 

356 filename (str): The full path to the credentials file. 

357 scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If 

358 specified, the credentials will automatically be scoped if 

359 necessary. 

360 default_scopes (Optional[Sequence[str]]): Default scopes passed by a 

361 Google client library. Use 'scopes' for user-defined scopes. 

362 request (Optional[google.auth.transport.Request]): An object used to make 

363 HTTP requests. This is used to determine the associated project ID 

364 for a workload identity pool resource (external account credentials). 

365 If not specified, then it will use a 

366 google.auth.transport.requests.Request client to make requests. 

367 

368 Returns: 

369 Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded 

370 credentials and the project ID. External account credentials project 

371 IDs may not always be determined. 

372 

373 Raises: 

374 google.auth.exceptions.DefaultCredentialsError: if the info dictionary 

375 is in the wrong format or is missing required information. 

376 """ 

377 # There are currently 3 types of external_account credentials. 

378 if info.get("subject_token_type") == _AWS_SUBJECT_TOKEN_TYPE: 

379 # Check if configuration corresponds to an AWS credentials. 

380 from google.auth import aws 

381 

382 credentials = aws.Credentials.from_info( 

383 info, scopes=scopes, default_scopes=default_scopes 

384 ) 

385 elif ( 

386 info.get("credential_source") is not None 

387 and info.get("credential_source").get("executable") is not None 

388 ): 

389 from google.auth import pluggable 

390 

391 credentials = pluggable.Credentials.from_info( 

392 info, scopes=scopes, default_scopes=default_scopes 

393 ) 

394 else: 

395 try: 

396 # Check if configuration corresponds to an Identity Pool credentials. 

397 from google.auth import identity_pool 

398 

399 credentials = identity_pool.Credentials.from_info( 

400 info, scopes=scopes, default_scopes=default_scopes 

401 ) 

402 except ValueError: 

403 # If the configuration is invalid or does not correspond to any 

404 # supported external_account credentials, raise an error. 

405 raise exceptions.DefaultCredentialsError( 

406 "Failed to load external account credentials from {}".format(filename) 

407 ) 

408 if request is None: 

409 import google.auth.transport.requests 

410 

411 request = google.auth.transport.requests.Request() 

412 

413 return credentials, credentials.get_project_id(request=request) 

414 

415 

416def _get_external_account_authorized_user_credentials( 

417 filename, info, scopes=None, default_scopes=None, request=None 

418): 

419 try: 

420 from google.auth import external_account_authorized_user 

421 

422 credentials = external_account_authorized_user.Credentials.from_info(info) 

423 except ValueError: 

424 raise exceptions.DefaultCredentialsError( 

425 "Failed to load external account authorized user credentials from {}".format( 

426 filename 

427 ) 

428 ) 

429 

430 return credentials, None 

431 

432 

433def _get_authorized_user_credentials(filename, info, scopes=None): 

434 from google.oauth2 import credentials 

435 

436 try: 

437 credentials = credentials.Credentials.from_authorized_user_info( 

438 info, scopes=scopes 

439 ) 

440 except ValueError as caught_exc: 

441 msg = "Failed to load authorized user credentials from {}".format(filename) 

442 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) 

443 six.raise_from(new_exc, caught_exc) 

444 return credentials, None 

445 

446 

447def _get_service_account_credentials(filename, info, scopes=None, default_scopes=None): 

448 from google.oauth2 import service_account 

449 

450 try: 

451 credentials = service_account.Credentials.from_service_account_info( 

452 info, scopes=scopes, default_scopes=default_scopes 

453 ) 

454 except ValueError as caught_exc: 

455 msg = "Failed to load service account credentials from {}".format(filename) 

456 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) 

457 six.raise_from(new_exc, caught_exc) 

458 return credentials, info.get("project_id") 

459 

460 

461def _get_impersonated_service_account_credentials(filename, info, scopes): 

462 from google.auth import impersonated_credentials 

463 

464 try: 

465 source_credentials_info = info.get("source_credentials") 

466 source_credentials_type = source_credentials_info.get("type") 

467 if source_credentials_type == _AUTHORIZED_USER_TYPE: 

468 source_credentials, _ = _get_authorized_user_credentials( 

469 filename, source_credentials_info 

470 ) 

471 elif source_credentials_type == _SERVICE_ACCOUNT_TYPE: 

472 source_credentials, _ = _get_service_account_credentials( 

473 filename, source_credentials_info 

474 ) 

475 else: 

476 raise exceptions.InvalidType( 

477 "source credential of type {} is not supported.".format( 

478 source_credentials_type 

479 ) 

480 ) 

481 impersonation_url = info.get("service_account_impersonation_url") 

482 start_index = impersonation_url.rfind("/") 

483 end_index = impersonation_url.find(":generateAccessToken") 

484 if start_index == -1 or end_index == -1 or start_index > end_index: 

485 raise exceptions.InvalidValue( 

486 "Cannot extract target principal from {}".format(impersonation_url) 

487 ) 

488 target_principal = impersonation_url[start_index + 1 : end_index] 

489 delegates = info.get("delegates") 

490 quota_project_id = info.get("quota_project_id") 

491 credentials = impersonated_credentials.Credentials( 

492 source_credentials, 

493 target_principal, 

494 scopes, 

495 delegates, 

496 quota_project_id=quota_project_id, 

497 ) 

498 except ValueError as caught_exc: 

499 msg = "Failed to load impersonated service account credentials from {}".format( 

500 filename 

501 ) 

502 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) 

503 six.raise_from(new_exc, caught_exc) 

504 return credentials, None 

505 

506 

507def _get_gdch_service_account_credentials(filename, info): 

508 from google.oauth2 import gdch_credentials 

509 

510 try: 

511 credentials = gdch_credentials.ServiceAccountCredentials.from_service_account_info( 

512 info 

513 ) 

514 except ValueError as caught_exc: 

515 msg = "Failed to load GDCH service account credentials from {}".format(filename) 

516 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) 

517 six.raise_from(new_exc, caught_exc) 

518 return credentials, info.get("project") 

519 

520 

521def get_api_key_credentials(key): 

522 """Return credentials with the given API key.""" 

523 from google.auth import api_key 

524 

525 return api_key.Credentials(key) 

526 

527 

528def _apply_quota_project_id(credentials, quota_project_id): 

529 if quota_project_id: 

530 credentials = credentials.with_quota_project(quota_project_id) 

531 else: 

532 credentials = credentials.with_quota_project_from_environment() 

533 

534 from google.oauth2 import credentials as authorized_user_credentials 

535 

536 if isinstance(credentials, authorized_user_credentials.Credentials) and ( 

537 not credentials.quota_project_id 

538 ): 

539 _warn_about_problematic_credentials(credentials) 

540 return credentials 

541 

542 

543def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): 

544 """Gets the default credentials for the current environment. 

545 

546 `Application Default Credentials`_ provides an easy way to obtain 

547 credentials to call Google APIs for server-to-server or local applications. 

548 This function acquires credentials from the environment in the following 

549 order: 

550 

551 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set 

552 to the path of a valid service account JSON private key file, then it is 

553 loaded and returned. The project ID returned is the project ID defined 

554 in the service account file if available (some older files do not 

555 contain project ID information). 

556 

557 If the environment variable is set to the path of a valid external 

558 account JSON configuration file (workload identity federation), then the 

559 configuration file is used to determine and retrieve the external 

560 credentials from the current environment (AWS, Azure, etc). 

561 These will then be exchanged for Google access tokens via the Google STS 

562 endpoint. 

563 The project ID returned in this case is the one corresponding to the 

564 underlying workload identity pool resource if determinable. 

565 

566 If the environment variable is set to the path of a valid GDCH service 

567 account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH 

568 credential will be returned. The project ID returned is the project 

569 specified in the JSON file. 

570 2. If the `Google Cloud SDK`_ is installed and has application default 

571 credentials set they are loaded and returned. 

572 

573 To enable application default credentials with the Cloud SDK run:: 

574 

575 gcloud auth application-default login 

576 

577 If the Cloud SDK has an active project, the project ID is returned. The 

578 active project can be set using:: 

579 

580 gcloud config set project 

581 

582 3. If the application is running in the `App Engine standard environment`_ 

583 (first generation) then the credentials and project ID from the 

584 `App Identity Service`_ are used. 

585 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or 

586 the `App Engine flexible environment`_ or the `App Engine standard 

587 environment`_ (second generation) then the credentials and project ID 

588 are obtained from the `Metadata Service`_. 

589 5. If no credentials are found, 

590 :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. 

591 

592 .. _Application Default Credentials: https://developers.google.com\ 

593 /identity/protocols/application-default-credentials 

594 .. _Google Cloud SDK: https://cloud.google.com/sdk 

595 .. _App Engine standard environment: https://cloud.google.com/appengine 

596 .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ 

597 /appidentity/ 

598 .. _Compute Engine: https://cloud.google.com/compute 

599 .. _App Engine flexible environment: https://cloud.google.com\ 

600 /appengine/flexible 

601 .. _Metadata Service: https://cloud.google.com/compute/docs\ 

602 /storing-retrieving-metadata 

603 .. _Cloud Run: https://cloud.google.com/run 

604 .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ 

605 /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted 

606 

607 Example:: 

608 

609 import google.auth 

610 

611 credentials, project_id = google.auth.default() 

612 

613 Args: 

614 scopes (Sequence[str]): The list of scopes for the credentials. If 

615 specified, the credentials will automatically be scoped if 

616 necessary. 

617 request (Optional[google.auth.transport.Request]): An object used to make 

618 HTTP requests. This is used to either detect whether the application 

619 is running on Compute Engine or to determine the associated project 

620 ID for a workload identity pool resource (external account 

621 credentials). If not specified, then it will either use the standard 

622 library http client to make requests for Compute Engine credentials 

623 or a google.auth.transport.requests.Request client for external 

624 account credentials. 

625 quota_project_id (Optional[str]): The project ID used for 

626 quota and billing. 

627 default_scopes (Optional[Sequence[str]]): Default scopes passed by a 

628 Google client library. Use 'scopes' for user-defined scopes. 

629 Returns: 

630 Tuple[~google.auth.credentials.Credentials, Optional[str]]: 

631 the current environment's credentials and project ID. Project ID 

632 may be None, which indicates that the Project ID could not be 

633 ascertained from the environment. 

634 

635 Raises: 

636 ~google.auth.exceptions.DefaultCredentialsError: 

637 If no credentials were found, or if the credentials found were 

638 invalid. 

639 """ 

640 from google.auth.credentials import with_scopes_if_required 

641 from google.auth.credentials import CredentialsWithQuotaProject 

642 

643 explicit_project_id = os.environ.get( 

644 environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) 

645 ) 

646 

647 checkers = ( 

648 # Avoid passing scopes here to prevent passing scopes to user credentials. 

649 # with_scopes_if_required() below will ensure scopes/default scopes are 

650 # safely set on the returned credentials since requires_scopes will 

651 # guard against setting scopes on user credentials. 

652 lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), 

653 lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), 

654 _get_gae_credentials, 

655 lambda: _get_gce_credentials(request, quota_project_id=quota_project_id), 

656 ) 

657 

658 for checker in checkers: 

659 credentials, project_id = checker() 

660 if credentials is not None: 

661 credentials = with_scopes_if_required( 

662 credentials, scopes, default_scopes=default_scopes 

663 ) 

664 

665 # For external account credentials, scopes are required to determine 

666 # the project ID. Try to get the project ID again if not yet 

667 # determined. 

668 if not project_id and callable( 

669 getattr(credentials, "get_project_id", None) 

670 ): 

671 if request is None: 

672 import google.auth.transport.requests 

673 

674 request = google.auth.transport.requests.Request() 

675 project_id = credentials.get_project_id(request=request) 

676 

677 if quota_project_id and isinstance( 

678 credentials, CredentialsWithQuotaProject 

679 ): 

680 credentials = credentials.with_quota_project(quota_project_id) 

681 

682 effective_project_id = explicit_project_id or project_id 

683 if not effective_project_id: 

684 _LOGGER.warning( 

685 "No project ID could be determined. Consider running " 

686 "`gcloud config set project` or setting the %s " 

687 "environment variable", 

688 environment_vars.PROJECT, 

689 ) 

690 return credentials, effective_project_id 

691 

692 raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS)