_default.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. credentials._cred_file_path = credentials_filename
  200. if not project_id:
  201. project_id = _cloud_sdk.get_project_id()
  202. return credentials, project_id
  203. def _get_explicit_environ_credentials(quota_project_id=None):
  204. """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
  205. variable."""
  206. from google.auth import _cloud_sdk
  207. cloud_sdk_adc_path = _cloud_sdk.get_application_default_credentials_path()
  208. explicit_file = os.environ.get(environment_vars.CREDENTIALS)
  209. _LOGGER.debug(
  210. "Checking %s for explicit credentials as part of auth process...", explicit_file
  211. )
  212. if explicit_file is not None and explicit_file == cloud_sdk_adc_path:
  213. # Cloud sdk flow calls gcloud to fetch project id, so if the explicit
  214. # file path is cloud sdk credentials path, then we should fall back
  215. # to cloud sdk flow, otherwise project id cannot be obtained.
  216. _LOGGER.debug(
  217. "Explicit credentials path %s is the same as Cloud SDK credentials path, fall back to Cloud SDK credentials flow...",
  218. explicit_file,
  219. )
  220. return _get_gcloud_sdk_credentials(quota_project_id=quota_project_id)
  221. if explicit_file is not None:
  222. credentials, project_id = load_credentials_from_file(
  223. os.environ[environment_vars.CREDENTIALS], quota_project_id=quota_project_id
  224. )
  225. credentials._cred_file_path = f"{explicit_file} file via the GOOGLE_APPLICATION_CREDENTIALS environment variable"
  226. return credentials, project_id
  227. else:
  228. return None, None
  229. def _get_gae_credentials():
  230. """Gets Google App Engine App Identity credentials and project ID."""
  231. # If not GAE gen1, prefer the metadata service even if the GAE APIs are
  232. # available as per https://google.aip.dev/auth/4115.
  233. if os.environ.get(environment_vars.LEGACY_APPENGINE_RUNTIME) != "python27":
  234. return None, None
  235. # While this library is normally bundled with app_engine, there are
  236. # some cases where it's not available, so we tolerate ImportError.
  237. try:
  238. _LOGGER.debug("Checking for App Engine runtime as part of auth process...")
  239. import google.auth.app_engine as app_engine
  240. except ImportError:
  241. _LOGGER.warning("Import of App Engine auth library failed.")
  242. return None, None
  243. try:
  244. credentials = app_engine.Credentials()
  245. project_id = app_engine.get_project_id()
  246. return credentials, project_id
  247. except EnvironmentError:
  248. _LOGGER.debug(
  249. "No App Engine library was found so cannot authentication via App Engine Identity Credentials."
  250. )
  251. return None, None
  252. def _get_gce_credentials(request=None, quota_project_id=None):
  253. """Gets credentials and project ID from the GCE Metadata Service."""
  254. # Ping requires a transport, but we want application default credentials
  255. # to require no arguments. So, we'll use the _http_client transport which
  256. # uses http.client. This is only acceptable because the metadata server
  257. # doesn't do SSL and never requires proxies.
  258. # While this library is normally bundled with compute_engine, there are
  259. # some cases where it's not available, so we tolerate ImportError.
  260. try:
  261. from google.auth import compute_engine
  262. from google.auth.compute_engine import _metadata
  263. except ImportError:
  264. _LOGGER.warning("Import of Compute Engine auth library failed.")
  265. return None, None
  266. if request is None:
  267. request = google.auth.transport._http_client.Request()
  268. if _metadata.is_on_gce(request=request):
  269. # Get the project ID.
  270. try:
  271. project_id = _metadata.get_project_id(request=request)
  272. except exceptions.TransportError:
  273. project_id = None
  274. cred = compute_engine.Credentials()
  275. cred = _apply_quota_project_id(cred, quota_project_id)
  276. return cred, project_id
  277. else:
  278. _LOGGER.warning(
  279. "Authentication failed using Compute Engine authentication due to unavailable metadata server."
  280. )
  281. return None, None
  282. def _get_external_account_credentials(
  283. info, filename, scopes=None, default_scopes=None, request=None
  284. ):
  285. """Loads external account Credentials from the parsed external account info.
  286. The credentials information must correspond to a supported external account
  287. credentials.
  288. Args:
  289. info (Mapping[str, str]): The external account info in Google format.
  290. filename (str): The full path to the credentials file.
  291. scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
  292. specified, the credentials will automatically be scoped if
  293. necessary.
  294. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  295. Google client library. Use 'scopes' for user-defined scopes.
  296. request (Optional[google.auth.transport.Request]): An object used to make
  297. HTTP requests. This is used to determine the associated project ID
  298. for a workload identity pool resource (external account credentials).
  299. If not specified, then it will use a
  300. google.auth.transport.requests.Request client to make requests.
  301. Returns:
  302. Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
  303. credentials and the project ID. External account credentials project
  304. IDs may not always be determined.
  305. Raises:
  306. google.auth.exceptions.DefaultCredentialsError: if the info dictionary
  307. is in the wrong format or is missing required information.
  308. """
  309. # There are currently 3 types of external_account credentials.
  310. if info.get("subject_token_type") == _AWS_SUBJECT_TOKEN_TYPE:
  311. # Check if configuration corresponds to an AWS credentials.
  312. from google.auth import aws
  313. credentials = aws.Credentials.from_info(
  314. info, scopes=scopes, default_scopes=default_scopes
  315. )
  316. elif (
  317. info.get("credential_source") is not None
  318. and info.get("credential_source").get("executable") is not None
  319. ):
  320. from google.auth import pluggable
  321. credentials = pluggable.Credentials.from_info(
  322. info, scopes=scopes, default_scopes=default_scopes
  323. )
  324. else:
  325. try:
  326. # Check if configuration corresponds to an Identity Pool credentials.
  327. from google.auth import identity_pool
  328. credentials = identity_pool.Credentials.from_info(
  329. info, scopes=scopes, default_scopes=default_scopes
  330. )
  331. except ValueError:
  332. # If the configuration is invalid or does not correspond to any
  333. # supported external_account credentials, raise an error.
  334. raise exceptions.DefaultCredentialsError(
  335. "Failed to load external account credentials from {}".format(filename)
  336. )
  337. if request is None:
  338. import google.auth.transport.requests
  339. request = google.auth.transport.requests.Request()
  340. return credentials, credentials.get_project_id(request=request)
  341. def _get_external_account_authorized_user_credentials(
  342. filename, info, scopes=None, default_scopes=None, request=None
  343. ):
  344. try:
  345. from google.auth import external_account_authorized_user
  346. credentials = external_account_authorized_user.Credentials.from_info(info)
  347. except ValueError:
  348. raise exceptions.DefaultCredentialsError(
  349. "Failed to load external account authorized user credentials from {}".format(
  350. filename
  351. )
  352. )
  353. return credentials, None
  354. def _get_authorized_user_credentials(filename, info, scopes=None):
  355. from google.oauth2 import credentials
  356. try:
  357. credentials = credentials.Credentials.from_authorized_user_info(
  358. info, scopes=scopes
  359. )
  360. except ValueError as caught_exc:
  361. msg = "Failed to load authorized user credentials from {}".format(filename)
  362. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  363. raise new_exc from caught_exc
  364. return credentials, None
  365. def _get_service_account_credentials(filename, info, scopes=None, default_scopes=None):
  366. from google.oauth2 import service_account
  367. try:
  368. credentials = service_account.Credentials.from_service_account_info(
  369. info, scopes=scopes, default_scopes=default_scopes
  370. )
  371. except ValueError as caught_exc:
  372. msg = "Failed to load service account credentials from {}".format(filename)
  373. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  374. raise new_exc from caught_exc
  375. return credentials, info.get("project_id")
  376. def _get_impersonated_service_account_credentials(filename, info, scopes):
  377. from google.auth import impersonated_credentials
  378. try:
  379. source_credentials_info = info.get("source_credentials")
  380. source_credentials_type = source_credentials_info.get("type")
  381. if source_credentials_type == _AUTHORIZED_USER_TYPE:
  382. source_credentials, _ = _get_authorized_user_credentials(
  383. filename, source_credentials_info
  384. )
  385. elif source_credentials_type == _SERVICE_ACCOUNT_TYPE:
  386. source_credentials, _ = _get_service_account_credentials(
  387. filename, source_credentials_info
  388. )
  389. elif source_credentials_type == _EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE:
  390. source_credentials, _ = _get_external_account_authorized_user_credentials(
  391. filename, source_credentials_info
  392. )
  393. else:
  394. raise exceptions.InvalidType(
  395. "source credential of type {} is not supported.".format(
  396. source_credentials_type
  397. )
  398. )
  399. impersonation_url = info.get("service_account_impersonation_url")
  400. start_index = impersonation_url.rfind("/")
  401. end_index = impersonation_url.find(":generateAccessToken")
  402. if start_index == -1 or end_index == -1 or start_index > end_index:
  403. raise exceptions.InvalidValue(
  404. "Cannot extract target principal from {}".format(impersonation_url)
  405. )
  406. target_principal = impersonation_url[start_index + 1 : end_index]
  407. delegates = info.get("delegates")
  408. quota_project_id = info.get("quota_project_id")
  409. credentials = impersonated_credentials.Credentials(
  410. source_credentials,
  411. target_principal,
  412. scopes,
  413. delegates,
  414. quota_project_id=quota_project_id,
  415. )
  416. except ValueError as caught_exc:
  417. msg = "Failed to load impersonated service account credentials from {}".format(
  418. filename
  419. )
  420. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  421. raise new_exc from caught_exc
  422. return credentials, None
  423. def _get_gdch_service_account_credentials(filename, info):
  424. from google.oauth2 import gdch_credentials
  425. try:
  426. credentials = gdch_credentials.ServiceAccountCredentials.from_service_account_info(
  427. info
  428. )
  429. except ValueError as caught_exc:
  430. msg = "Failed to load GDCH service account credentials from {}".format(filename)
  431. new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
  432. raise new_exc from caught_exc
  433. return credentials, info.get("project")
  434. def get_api_key_credentials(key):
  435. """Return credentials with the given API key."""
  436. from google.auth import api_key
  437. return api_key.Credentials(key)
  438. def _apply_quota_project_id(credentials, quota_project_id):
  439. if quota_project_id:
  440. credentials = credentials.with_quota_project(quota_project_id)
  441. else:
  442. credentials = credentials.with_quota_project_from_environment()
  443. from google.oauth2 import credentials as authorized_user_credentials
  444. if isinstance(credentials, authorized_user_credentials.Credentials) and (
  445. not credentials.quota_project_id
  446. ):
  447. _warn_about_problematic_credentials(credentials)
  448. return credentials
  449. def default(scopes=None, request=None, quota_project_id=None, default_scopes=None):
  450. """Gets the default credentials for the current environment.
  451. `Application Default Credentials`_ provides an easy way to obtain
  452. credentials to call Google APIs for server-to-server or local applications.
  453. This function acquires credentials from the environment in the following
  454. order:
  455. 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
  456. to the path of a valid service account JSON private key file, then it is
  457. loaded and returned. The project ID returned is the project ID defined
  458. in the service account file if available (some older files do not
  459. contain project ID information).
  460. If the environment variable is set to the path of a valid external
  461. account JSON configuration file (workload identity federation), then the
  462. configuration file is used to determine and retrieve the external
  463. credentials from the current environment (AWS, Azure, etc).
  464. These will then be exchanged for Google access tokens via the Google STS
  465. endpoint.
  466. The project ID returned in this case is the one corresponding to the
  467. underlying workload identity pool resource if determinable.
  468. If the environment variable is set to the path of a valid GDCH service
  469. account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH
  470. credential will be returned. The project ID returned is the project
  471. specified in the JSON file.
  472. 2. If the `Google Cloud SDK`_ is installed and has application default
  473. credentials set they are loaded and returned.
  474. To enable application default credentials with the Cloud SDK run::
  475. gcloud auth application-default login
  476. If the Cloud SDK has an active project, the project ID is returned. The
  477. active project can be set using::
  478. gcloud config set project
  479. 3. If the application is running in the `App Engine standard environment`_
  480. (first generation) then the credentials and project ID from the
  481. `App Identity Service`_ are used.
  482. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or
  483. the `App Engine flexible environment`_ or the `App Engine standard
  484. environment`_ (second generation) then the credentials and project ID
  485. are obtained from the `Metadata Service`_.
  486. 5. If no credentials are found,
  487. :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
  488. .. _Application Default Credentials: https://developers.google.com\
  489. /identity/protocols/application-default-credentials
  490. .. _Google Cloud SDK: https://cloud.google.com/sdk
  491. .. _App Engine standard environment: https://cloud.google.com/appengine
  492. .. _App Identity Service: https://cloud.google.com/appengine/docs/python\
  493. /appidentity/
  494. .. _Compute Engine: https://cloud.google.com/compute
  495. .. _App Engine flexible environment: https://cloud.google.com\
  496. /appengine/flexible
  497. .. _Metadata Service: https://cloud.google.com/compute/docs\
  498. /storing-retrieving-metadata
  499. .. _Cloud Run: https://cloud.google.com/run
  500. .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\
  501. /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted
  502. Example::
  503. import google.auth
  504. credentials, project_id = google.auth.default()
  505. Args:
  506. scopes (Sequence[str]): The list of scopes for the credentials. If
  507. specified, the credentials will automatically be scoped if
  508. necessary.
  509. request (Optional[google.auth.transport.Request]): An object used to make
  510. HTTP requests. This is used to either detect whether the application
  511. is running on Compute Engine or to determine the associated project
  512. ID for a workload identity pool resource (external account
  513. credentials). If not specified, then it will either use the standard
  514. library http client to make requests for Compute Engine credentials
  515. or a google.auth.transport.requests.Request client for external
  516. account credentials.
  517. quota_project_id (Optional[str]): The project ID used for
  518. quota and billing.
  519. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  520. Google client library. Use 'scopes' for user-defined scopes.
  521. Returns:
  522. Tuple[~google.auth.credentials.Credentials, Optional[str]]:
  523. the current environment's credentials and project ID. Project ID
  524. may be None, which indicates that the Project ID could not be
  525. ascertained from the environment.
  526. Raises:
  527. ~google.auth.exceptions.DefaultCredentialsError:
  528. If no credentials were found, or if the credentials found were
  529. invalid.
  530. """
  531. from google.auth.credentials import with_scopes_if_required
  532. from google.auth.credentials import CredentialsWithQuotaProject
  533. explicit_project_id = os.environ.get(
  534. environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)
  535. )
  536. checkers = (
  537. # Avoid passing scopes here to prevent passing scopes to user credentials.
  538. # with_scopes_if_required() below will ensure scopes/default scopes are
  539. # safely set on the returned credentials since requires_scopes will
  540. # guard against setting scopes on user credentials.
  541. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id),
  542. lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id),
  543. _get_gae_credentials,
  544. lambda: _get_gce_credentials(request, quota_project_id=quota_project_id),
  545. )
  546. for checker in checkers:
  547. credentials, project_id = checker()
  548. if credentials is not None:
  549. credentials = with_scopes_if_required(
  550. credentials, scopes, default_scopes=default_scopes
  551. )
  552. effective_project_id = explicit_project_id or project_id
  553. # For external account credentials, scopes are required to determine
  554. # the project ID. Try to get the project ID again if not yet
  555. # determined.
  556. if not effective_project_id and callable(
  557. getattr(credentials, "get_project_id", None)
  558. ):
  559. if request is None:
  560. import google.auth.transport.requests
  561. request = google.auth.transport.requests.Request()
  562. effective_project_id = credentials.get_project_id(request=request)
  563. if quota_project_id and isinstance(
  564. credentials, CredentialsWithQuotaProject
  565. ):
  566. credentials = credentials.with_quota_project(quota_project_id)
  567. if not effective_project_id:
  568. _LOGGER.warning(
  569. "No project ID could be determined. Consider running "
  570. "`gcloud config set project` or setting the %s "
  571. "environment variable",
  572. environment_vars.PROJECT,
  573. )
  574. return credentials, effective_project_id
  575. raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS)