_default.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. """Application default credentials.
  15. Implements application default credentials and project ID detection.
  16. """
  17. import io
  18. import json
  19. import logging
  20. import os
  21. import warnings
  22. from google.auth import environment_vars
  23. from google.auth import exceptions
  24. import google.auth.transport._http_client
  25. _LOGGER = logging.getLogger(__name__)
  26. # Valid types accepted for file-based credentials.
  27. _AUTHORIZED_USER_TYPE = "authorized_user"
  28. _SERVICE_ACCOUNT_TYPE = "service_account"
  29. _EXTERNAL_ACCOUNT_TYPE = "external_account"
  30. _EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user"
  31. _IMPERSONATED_SERVICE_ACCOUNT_TYPE = "impersonated_service_account"
  32. _GDCH_SERVICE_ACCOUNT_TYPE = "gdch_service_account"
  33. _VALID_TYPES = (
  34. _AUTHORIZED_USER_TYPE,
  35. _SERVICE_ACCOUNT_TYPE,
  36. _EXTERNAL_ACCOUNT_TYPE,
  37. _EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE,
  38. _IMPERSONATED_SERVICE_ACCOUNT_TYPE,
  39. _GDCH_SERVICE_ACCOUNT_TYPE,
  40. )
  41. # Help message when no credentials can be found.
  42. _CLOUD_SDK_MISSING_CREDENTIALS = """\
  43. Your default credentials were not found. To set up Application Default Credentials, \
  44. see https://cloud.google.com/docs/authentication/external/set-up-adc for more information.\
  45. """
  46. # Warning when using Cloud SDK user credentials
  47. _CLOUD_SDK_CREDENTIALS_WARNING = """\
  48. Your application has authenticated using end user credentials from Google \
  49. Cloud SDK without a quota project. You might receive a "quota exceeded" \
  50. or "API not enabled" error. See the following page for troubleshooting: \
  51. https://cloud.google.com/docs/authentication/adc-troubleshooting/user-creds. \
  52. """
  53. # The subject token type used for AWS external_account credentials.
  54. _AWS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:aws:token-type:aws4_request"
  55. def _warn_about_problematic_credentials(credentials):
  56. """Determines if the credentials are problematic.
  57. Credentials from the Cloud SDK that are associated with Cloud SDK's project
  58. are problematic because they may not have APIs enabled and have limited
  59. quota. If this is the case, warn about it.
  60. """
  61. from google.auth import _cloud_sdk
  62. if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:
  63. warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)
  64. def load_credentials_from_file(
  65. filename, scopes=None, default_scopes=None, quota_project_id=None, request=None
  66. ):
  67. """Loads Google credentials from a file.
  68. The credentials file must be a service account key, stored authorized
  69. user credentials, external account credentials, or impersonated service
  70. account credentials.
  71. Args:
  72. filename (str): The full path to the credentials file.
  73. scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
  74. specified, the credentials will automatically be scoped if
  75. necessary
  76. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  77. Google client library. Use 'scopes' for user-defined scopes.
  78. quota_project_id (Optional[str]): The project ID used for
  79. quota and billing.
  80. request (Optional[google.auth.transport.Request]): An object used to make
  81. HTTP requests. This is used to determine the associated project ID
  82. for a workload identity pool resource (external account credentials).
  83. If not specified, then it will use a
  84. google.auth.transport.requests.Request client to make requests.
  85. Returns:
  86. Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
  87. credentials and the project ID. Authorized user credentials do not
  88. have the project ID information. External account credentials project
  89. IDs may not always be determined.
  90. Raises:
  91. google.auth.exceptions.DefaultCredentialsError: if the file is in the
  92. wrong format or is missing.
  93. """
  94. if not os.path.exists(filename):
  95. raise exceptions.DefaultCredentialsError(
  96. "File {} was not found.".format(filename)
  97. )
  98. with io.open(filename, "r") as file_obj:
  99. try:
  100. info = json.load(file_obj)
  101. except ValueError as caught_exc:
  102. new_exc = exceptions.DefaultCredentialsError(
  103. "File {} is not a valid json file.".format(filename), caught_exc
  104. )
  105. raise new_exc from caught_exc
  106. return _load_credentials_from_info(
  107. filename, info, scopes, default_scopes, quota_project_id, request
  108. )
  109. def load_credentials_from_dict(
  110. info, scopes=None, default_scopes=None, quota_project_id=None, request=None
  111. ):
  112. """Loads Google credentials from a dict.
  113. The credentials file must be a service account key, stored authorized
  114. user credentials, external account credentials, or impersonated service
  115. account credentials.
  116. Args:
  117. info (Dict[str, Any]): A dict object containing the credentials
  118. scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
  119. specified, the credentials will automatically be scoped if
  120. necessary
  121. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  122. Google client library. Use 'scopes' for user-defined scopes.
  123. quota_project_id (Optional[str]): The project ID used for
  124. quota and billing.
  125. request (Optional[google.auth.transport.Request]): An object used to make
  126. HTTP requests. This is used to determine the associated project ID
  127. for a workload identity pool resource (external account credentials).
  128. If not specified, then it will use a
  129. google.auth.transport.requests.Request client to make requests.
  130. Returns:
  131. Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
  132. credentials and the project ID. Authorized user credentials do not
  133. have the project ID information. External account credentials project
  134. IDs may not always be determined.
  135. Raises:
  136. google.auth.exceptions.DefaultCredentialsError: if the file is in the
  137. wrong format or is missing.
  138. """
  139. if not isinstance(info, dict):
  140. raise exceptions.DefaultCredentialsError(
  141. "info object was of type {} but dict type was expected.".format(type(info))
  142. )
  143. return _load_credentials_from_info(
  144. "dict object", info, scopes, default_scopes, quota_project_id, request
  145. )
  146. def _load_credentials_from_info(
  147. filename, info, scopes, default_scopes, quota_project_id, request
  148. ):
  149. from google.auth.credentials import CredentialsWithQuotaProject
  150. credential_type = info.get("type")
  151. if credential_type == _AUTHORIZED_USER_TYPE:
  152. credentials, project_id = _get_authorized_user_credentials(
  153. filename, info, scopes
  154. )
  155. elif credential_type == _SERVICE_ACCOUNT_TYPE:
  156. credentials, project_id = _get_service_account_credentials(
  157. filename, info, scopes, default_scopes
  158. )
  159. elif credential_type == _EXTERNAL_ACCOUNT_TYPE:
  160. credentials, project_id = _get_external_account_credentials(
  161. info,
  162. filename,
  163. scopes=scopes,
  164. default_scopes=default_scopes,
  165. request=request,
  166. )
  167. elif credential_type == _EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE:
  168. credentials, project_id = _get_external_account_authorized_user_credentials(
  169. filename, info, request
  170. )
  171. elif credential_type == _IMPERSONATED_SERVICE_ACCOUNT_TYPE:
  172. credentials, project_id = _get_impersonated_service_account_credentials(
  173. filename, info, scopes
  174. )
  175. elif credential_type == _GDCH_SERVICE_ACCOUNT_TYPE:
  176. credentials, project_id = _get_gdch_service_account_credentials(filename, info)
  177. else:
  178. raise exceptions.DefaultCredentialsError(
  179. "The file {file} does not have a valid type. "
  180. "Type is {type}, expected one of {valid_types}.".format(
  181. file=filename, type=credential_type, valid_types=_VALID_TYPES
  182. )
  183. )
  184. if isinstance(credentials, CredentialsWithQuotaProject):
  185. credentials = _apply_quota_project_id(credentials, quota_project_id)
  186. return credentials, project_id
  187. def _get_gcloud_sdk_credentials(quota_project_id=None):
  188. """Gets the credentials and project ID from the Cloud SDK."""
  189. from google.auth import _cloud_sdk
  190. _LOGGER.debug("Checking Cloud SDK credentials as part of auth process...")
  191. # Check if application default credentials exist.
  192. credentials_filename = _cloud_sdk.get_application_default_credentials_path()
  193. if not os.path.isfile(credentials_filename):
  194. _LOGGER.debug("Cloud SDK credentials not found on disk; not using them")
  195. return None, None
  196. credentials, project_id = load_credentials_from_file(
  197. credentials_filename, quota_project_id=quota_project_id
  198. )
  199. if not project_id:
  200. project_id = _cloud_sdk.get_project_id()
  201. return credentials, project_id
  202. def _get_explicit_environ_credentials(quota_project_id=None):
  203. """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
  204. variable."""
  205. from google.auth import _cloud_sdk
  206. cloud_sdk_adc_path = _cloud_sdk.get_application_default_credentials_path()
  207. explicit_file = os.environ.get(environment_vars.CREDENTIALS)
  208. _LOGGER.debug(
  209. "Checking %s for explicit credentials as part of auth process...", explicit_file
  210. )
  211. if explicit_file is not None and explicit_file == cloud_sdk_adc_path:
  212. # Cloud sdk flow calls gcloud to fetch project id, so if the explicit
  213. # file path is cloud sdk credentials path, then we should fall back
  214. # to cloud sdk flow, otherwise project id cannot be obtained.
  215. _LOGGER.debug(
  216. "Explicit credentials path %s is the same as Cloud SDK credentials path, fall back to Cloud SDK credentials flow...",
  217. explicit_file,
  218. )
  219. return _get_gcloud_sdk_credentials(quota_project_id=quota_project_id)
  220. if explicit_file is not None:
  221. credentials, project_id = load_credentials_from_file(
  222. os.environ[environment_vars.CREDENTIALS], quota_project_id=quota_project_id
  223. )
  224. return credentials, project_id
  225. else:
  226. return None, None
  227. def _get_gae_credentials():
  228. """Gets Google App Engine App Identity credentials and project ID."""
  229. # If not GAE gen1, prefer the metadata service even if the GAE APIs are
  230. # available as per https://google.aip.dev/auth/4115.
  231. if os.environ.get(environment_vars.LEGACY_APPENGINE_RUNTIME) != "python27":
  232. return None, None
  233. # While this library is normally bundled with app_engine, there are
  234. # some cases where it's not available, so we tolerate ImportError.
  235. try:
  236. _LOGGER.debug("Checking for App Engine runtime as part of auth process...")
  237. import google.auth.app_engine as app_engine
  238. except ImportError:
  239. _LOGGER.warning("Import of App Engine auth library failed.")
  240. return None, None
  241. try:
  242. credentials = app_engine.Credentials()
  243. project_id = app_engine.get_project_id()
  244. return credentials, project_id
  245. except EnvironmentError:
  246. _LOGGER.debug(
  247. "No App Engine library was found so cannot authentication via App Engine Identity Credentials."
  248. )
  249. return None, None
  250. def _get_gce_credentials(request=None, quota_project_id=None):
  251. """Gets credentials and project ID from the GCE Metadata Service."""
  252. # Ping requires a transport, but we want application default credentials
  253. # to require no arguments. So, we'll use the _http_client transport which
  254. # uses http.client. This is only acceptable because the metadata server
  255. # doesn't do SSL and never requires proxies.
  256. # While this library is normally bundled with compute_engine, there are
  257. # some cases where it's not available, so we tolerate ImportError.
  258. try:
  259. from google.auth import compute_engine
  260. from google.auth.compute_engine import _metadata
  261. except ImportError:
  262. _LOGGER.warning("Import of Compute Engine auth library failed.")
  263. return None, None
  264. if request is None:
  265. request = google.auth.transport._http_client.Request()
  266. if _metadata.is_on_gce(request=request):
  267. # Get the project ID.
  268. try:
  269. project_id = _metadata.get_project_id(request=request)
  270. except exceptions.TransportError:
  271. project_id = None
  272. cred = compute_engine.Credentials()
  273. cred = _apply_quota_project_id(cred, quota_project_id)
  274. return cred, project_id
  275. else:
  276. _LOGGER.warning(
  277. "Authentication failed using Compute Engine authentication due to unavailable metadata server."
  278. )
  279. return None, None
  280. def _get_external_account_credentials(
  281. info, filename, scopes=None, default_scopes=None, request=None
  282. ):
  283. """Loads external account Credentials from the parsed external account info.
  284. The credentials information must correspond to a supported external account
  285. credentials.
  286. Args:
  287. info (Mapping[str, str]): The external account info in Google format.
  288. filename (str): The full path to the credentials file.
  289. scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
  290. specified, the credentials will automatically be scoped if
  291. necessary.
  292. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  293. Google client library. Use 'scopes' for user-defined scopes.
  294. request (Optional[google.auth.transport.Request]): An object used to make
  295. HTTP requests. This is used to determine the associated project ID
  296. for a workload identity pool resource (external account credentials).
  297. If not specified, then it will use a
  298. google.auth.transport.requests.Request client to make requests.
  299. Returns:
  300. Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
  301. credentials and the project ID. External account credentials project
  302. IDs may not always be determined.
  303. Raises:
  304. google.auth.exceptions.DefaultCredentialsError: if the info dictionary
  305. is in the wrong format or is missing required information.
  306. """
  307. # There are currently 3 types of external_account credentials.
  308. if info.get("subject_token_type") == _AWS_SUBJECT_TOKEN_TYPE:
  309. # Check if configuration corresponds to an AWS credentials.
  310. from google.auth import aws
  311. credentials = aws.Credentials.from_info(
  312. info, scopes=scopes, default_scopes=default_scopes
  313. )
  314. elif (
  315. info.get("credential_source") is not None
  316. and info.get("credential_source").get("executable") is not None
  317. ):
  318. from google.auth import pluggable
  319. credentials = pluggable.Credentials.from_info(
  320. info, scopes=scopes, default_scopes=default_scopes
  321. )
  322. else:
  323. try:
  324. # Check if configuration corresponds to an Identity Pool credentials.
  325. from google.auth import identity_pool
  326. credentials = identity_pool.Credentials.from_info(
  327. info, scopes=scopes, default_scopes=default_scopes
  328. )
  329. except ValueError:
  330. # If the configuration is invalid or does not correspond to any
  331. # supported external_account credentials, raise an error.
  332. raise exceptions.DefaultCredentialsError(
  333. "Failed to load external account credentials from {}".format(filename)
  334. )
  335. if request is None:
  336. import google.auth.transport.requests
  337. request = google.auth.transport.requests.Request()
  338. return credentials, credentials.get_project_id(request=request)
  339. def _get_external_account_authorized_user_credentials(
  340. filename, info, scopes=None, default_scopes=None, request=None
  341. ):
  342. try:
  343. from google.auth import external_account_authorized_user
  344. credentials = external_account_authorized_user.Credentials.from_info(info)
  345. except ValueError:
  346. raise exceptions.DefaultCredentialsError(
  347. "Failed to load external account authorized user credentials from {}".format(
  348. filename
  349. )
  350. )
  351. return credentials, None
  352. def _get_authorized_user_credentials(filename, info, scopes=None):
  353. from google.oauth2 import credentials
  354. try:
  355. credentials = credentials.Credentials.from_authorized_user_info(
  356. info, scopes=scopes
  357. )
  358. except ValueError as caught_exc:
  359. msg = "Failed to load authorized user credentials from {}".format(filename)
  360. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  361. raise new_exc from caught_exc
  362. return credentials, None
  363. def _get_service_account_credentials(filename, info, scopes=None, default_scopes=None):
  364. from google.oauth2 import service_account
  365. try:
  366. credentials = service_account.Credentials.from_service_account_info(
  367. info, scopes=scopes, default_scopes=default_scopes
  368. )
  369. except ValueError as caught_exc:
  370. msg = "Failed to load service account credentials from {}".format(filename)
  371. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  372. raise new_exc from caught_exc
  373. return credentials, info.get("project_id")
  374. def _get_impersonated_service_account_credentials(filename, info, scopes):
  375. from google.auth import impersonated_credentials
  376. try:
  377. source_credentials_info = info.get("source_credentials")
  378. source_credentials_type = source_credentials_info.get("type")
  379. if source_credentials_type == _AUTHORIZED_USER_TYPE:
  380. source_credentials, _ = _get_authorized_user_credentials(
  381. filename, source_credentials_info
  382. )
  383. elif source_credentials_type == _SERVICE_ACCOUNT_TYPE:
  384. source_credentials, _ = _get_service_account_credentials(
  385. filename, source_credentials_info
  386. )
  387. else:
  388. raise exceptions.InvalidType(
  389. "source credential of type {} is not supported.".format(
  390. source_credentials_type
  391. )
  392. )
  393. impersonation_url = info.get("service_account_impersonation_url")
  394. start_index = impersonation_url.rfind("/")
  395. end_index = impersonation_url.find(":generateAccessToken")
  396. if start_index == -1 or end_index == -1 or start_index > end_index:
  397. raise exceptions.InvalidValue(
  398. "Cannot extract target principal from {}".format(impersonation_url)
  399. )
  400. target_principal = impersonation_url[start_index + 1 : end_index]
  401. delegates = info.get("delegates")
  402. quota_project_id = info.get("quota_project_id")
  403. credentials = impersonated_credentials.Credentials(
  404. source_credentials,
  405. target_principal,
  406. scopes,
  407. delegates,
  408. quota_project_id=quota_project_id,
  409. )
  410. except ValueError as caught_exc:
  411. msg = "Failed to load impersonated service account credentials from {}".format(
  412. filename
  413. )
  414. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  415. raise new_exc from caught_exc
  416. return credentials, None
  417. def _get_gdch_service_account_credentials(filename, info):
  418. from google.oauth2 import gdch_credentials
  419. try:
  420. credentials = gdch_credentials.ServiceAccountCredentials.from_service_account_info(
  421. info
  422. )
  423. except ValueError as caught_exc:
  424. msg = "Failed to load GDCH service account credentials from {}".format(filename)
  425. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  426. raise new_exc from caught_exc
  427. return credentials, info.get("project")
  428. def get_api_key_credentials(key):
  429. """Return credentials with the given API key."""
  430. from google.auth import api_key
  431. return api_key.Credentials(key)
  432. def _apply_quota_project_id(credentials, quota_project_id):
  433. if quota_project_id:
  434. credentials = credentials.with_quota_project(quota_project_id)
  435. else:
  436. credentials = credentials.with_quota_project_from_environment()
  437. from google.oauth2 import credentials as authorized_user_credentials
  438. if isinstance(credentials, authorized_user_credentials.Credentials) and (
  439. not credentials.quota_project_id
  440. ):
  441. _warn_about_problematic_credentials(credentials)
  442. return credentials
  443. def default(scopes=None, request=None, quota_project_id=None, default_scopes=None):
  444. """Gets the default credentials for the current environment.
  445. `Application Default Credentials`_ provides an easy way to obtain
  446. credentials to call Google APIs for server-to-server or local applications.
  447. This function acquires credentials from the environment in the following
  448. order:
  449. 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
  450. to the path of a valid service account JSON private key file, then it is
  451. loaded and returned. The project ID returned is the project ID defined
  452. in the service account file if available (some older files do not
  453. contain project ID information).
  454. If the environment variable is set to the path of a valid external
  455. account JSON configuration file (workload identity federation), then the
  456. configuration file is used to determine and retrieve the external
  457. credentials from the current environment (AWS, Azure, etc).
  458. These will then be exchanged for Google access tokens via the Google STS
  459. endpoint.
  460. The project ID returned in this case is the one corresponding to the
  461. underlying workload identity pool resource if determinable.
  462. If the environment variable is set to the path of a valid GDCH service
  463. account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH
  464. credential will be returned. The project ID returned is the project
  465. specified in the JSON file.
  466. 2. If the `Google Cloud SDK`_ is installed and has application default
  467. credentials set they are loaded and returned.
  468. To enable application default credentials with the Cloud SDK run::
  469. gcloud auth application-default login
  470. If the Cloud SDK has an active project, the project ID is returned. The
  471. active project can be set using::
  472. gcloud config set project
  473. 3. If the application is running in the `App Engine standard environment`_
  474. (first generation) then the credentials and project ID from the
  475. `App Identity Service`_ are used.
  476. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or
  477. the `App Engine flexible environment`_ or the `App Engine standard
  478. environment`_ (second generation) then the credentials and project ID
  479. are obtained from the `Metadata Service`_.
  480. 5. If no credentials are found,
  481. :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
  482. .. _Application Default Credentials: https://developers.google.com\
  483. /identity/protocols/application-default-credentials
  484. .. _Google Cloud SDK: https://cloud.google.com/sdk
  485. .. _App Engine standard environment: https://cloud.google.com/appengine
  486. .. _App Identity Service: https://cloud.google.com/appengine/docs/python\
  487. /appidentity/
  488. .. _Compute Engine: https://cloud.google.com/compute
  489. .. _App Engine flexible environment: https://cloud.google.com\
  490. /appengine/flexible
  491. .. _Metadata Service: https://cloud.google.com/compute/docs\
  492. /storing-retrieving-metadata
  493. .. _Cloud Run: https://cloud.google.com/run
  494. .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\
  495. /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted
  496. Example::
  497. import google.auth
  498. credentials, project_id = google.auth.default()
  499. Args:
  500. scopes (Sequence[str]): The list of scopes for the credentials. If
  501. specified, the credentials will automatically be scoped if
  502. necessary.
  503. request (Optional[google.auth.transport.Request]): An object used to make
  504. HTTP requests. This is used to either detect whether the application
  505. is running on Compute Engine or to determine the associated project
  506. ID for a workload identity pool resource (external account
  507. credentials). If not specified, then it will either use the standard
  508. library http client to make requests for Compute Engine credentials
  509. or a google.auth.transport.requests.Request client for external
  510. account credentials.
  511. quota_project_id (Optional[str]): The project ID used for
  512. quota and billing.
  513. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  514. Google client library. Use 'scopes' for user-defined scopes.
  515. Returns:
  516. Tuple[~google.auth.credentials.Credentials, Optional[str]]:
  517. the current environment's credentials and project ID. Project ID
  518. may be None, which indicates that the Project ID could not be
  519. ascertained from the environment.
  520. Raises:
  521. ~google.auth.exceptions.DefaultCredentialsError:
  522. If no credentials were found, or if the credentials found were
  523. invalid.
  524. """
  525. from google.auth.credentials import with_scopes_if_required
  526. from google.auth.credentials import CredentialsWithQuotaProject
  527. explicit_project_id = os.environ.get(
  528. environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)
  529. )
  530. checkers = (
  531. # Avoid passing scopes here to prevent passing scopes to user credentials.
  532. # with_scopes_if_required() below will ensure scopes/default scopes are
  533. # safely set on the returned credentials since requires_scopes will
  534. # guard against setting scopes on user credentials.
  535. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id),
  536. lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id),
  537. _get_gae_credentials,
  538. lambda: _get_gce_credentials(request, quota_project_id=quota_project_id),
  539. )
  540. for checker in checkers:
  541. credentials, project_id = checker()
  542. if credentials is not None:
  543. credentials = with_scopes_if_required(
  544. credentials, scopes, default_scopes=default_scopes
  545. )
  546. effective_project_id = explicit_project_id or project_id
  547. # For external account credentials, scopes are required to determine
  548. # the project ID. Try to get the project ID again if not yet
  549. # determined.
  550. if not effective_project_id and callable(
  551. getattr(credentials, "get_project_id", None)
  552. ):
  553. if request is None:
  554. import google.auth.transport.requests
  555. request = google.auth.transport.requests.Request()
  556. effective_project_id = credentials.get_project_id(request=request)
  557. if quota_project_id and isinstance(
  558. credentials, CredentialsWithQuotaProject
  559. ):
  560. credentials = credentials.with_quota_project(quota_project_id)
  561. if not effective_project_id:
  562. _LOGGER.warning(
  563. "No project ID could be determined. Consider running "
  564. "`gcloud config set project` or setting the %s "
  565. "environment variable",
  566. environment_vars.PROJECT,
  567. )
  568. return credentials, effective_project_id
  569. raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS)