blob: de81c5b2c6c295a7f8d1b783627256d3d938669b [file] [log] [blame]
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -07001# 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
Thea Flowersa8d93482018-05-31 14:52:06 -070024import warnings
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070025
Danny Hermes895e3692017-11-09 11:35:57 -080026import six
27
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070028from google.auth import environment_vars
29from google.auth import exceptions
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070030import google.auth.transport._http_client
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070031
32_LOGGER = logging.getLogger(__name__)
33
34# Valid types accepted for file-based credentials.
Bu Sun Kim9eec0912019-10-21 17:04:21 -070035_AUTHORIZED_USER_TYPE = "authorized_user"
36_SERVICE_ACCOUNT_TYPE = "service_account"
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070037_VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE)
38
39# Help message when no credentials can be found.
Thea Flowersa8d93482018-05-31 14:52:06 -070040_HELP_MESSAGE = """\
41Could not automatically determine credentials. Please set {env} or \
42explicitly create credentials and re-run the application. For more \
43information, please see \
Christopher Wilcoxf1028252018-09-21 10:03:04 -070044https://cloud.google.com/docs/authentication/getting-started
Bu Sun Kim9eec0912019-10-21 17:04:21 -070045""".format(
46 env=environment_vars.CREDENTIALS
47).strip()
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070048
Thea Flowersa8d93482018-05-31 14:52:06 -070049# Warning when using Cloud SDK user credentials
50_CLOUD_SDK_CREDENTIALS_WARNING = """\
51Your application has authenticated using end user credentials from Google \
arithmetic1728f30b45a2020-06-17 23:36:04 -070052Cloud SDK without a quota project. You might receive a "quota exceeded" \
53or "API not enabled" error. We recommend you rerun \
54`gcloud auth application-default login` and make sure a quota project is \
55added. Or you can use service accounts instead. For more information \
56about service accounts, see https://cloud.google.com/docs/authentication/"""
Thea Flowersa8d93482018-05-31 14:52:06 -070057
58
59def _warn_about_problematic_credentials(credentials):
60 """Determines if the credentials are problematic.
61
62 Credentials from the Cloud SDK that are associated with Cloud SDK's project
63 are problematic because they may not have APIs enabled and have limited
64 quota. If this is the case, warn about it.
65 """
66 from google.auth import _cloud_sdk
Bu Sun Kim9eec0912019-10-21 17:04:21 -070067
Thea Flowersa8d93482018-05-31 14:52:06 -070068 if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:
69 warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)
70
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070071
Bu Sun Kim3dda7b22020-07-09 10:39:39 -070072def load_credentials_from_file(filename, scopes=None, quota_project_id=None):
Bu Sun Kim15d5fa92020-06-18 14:05:40 -070073 """Loads Google credentials from a file.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070074
75 The credentials file must be a service account key or stored authorized
76 user credentials.
77
78 Args:
79 filename (str): The full path to the credentials file.
Bu Sun Kim15d5fa92020-06-18 14:05:40 -070080 scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
81 specified, the credentials will automatically be scoped if
Bu Sun Kim3dda7b22020-07-09 10:39:39 -070082 necessary
83 quota_project_id (Optional[str]): The project ID used for
84 quota and billing.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070085
86 Returns:
87 Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
88 credentials and the project ID. Authorized user credentials do not
89 have the project ID information.
90
91 Raises:
92 google.auth.exceptions.DefaultCredentialsError: if the file is in the
weitaiting6e86c932017-08-12 03:26:59 +080093 wrong format or is missing.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070094 """
weitaiting6e86c932017-08-12 03:26:59 +080095 if not os.path.exists(filename):
96 raise exceptions.DefaultCredentialsError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -070097 "File {} was not found.".format(filename)
98 )
weitaiting6e86c932017-08-12 03:26:59 +080099
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700100 with io.open(filename, "r") as file_obj:
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700101 try:
102 info = json.load(file_obj)
Danny Hermes895e3692017-11-09 11:35:57 -0800103 except ValueError as caught_exc:
104 new_exc = exceptions.DefaultCredentialsError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700105 "File {} is not a valid json file.".format(filename), caught_exc
106 )
Danny Hermes895e3692017-11-09 11:35:57 -0800107 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700108
109 # The type key should indicate that the file is either a service account
110 # credentials file or an authorized user credentials file.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700111 credential_type = info.get("type")
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700112
113 if credential_type == _AUTHORIZED_USER_TYPE:
arithmetic1728772dac62020-03-27 14:34:13 -0700114 from google.oauth2 import credentials
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800115
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700116 try:
Bu Sun Kim15d5fa92020-06-18 14:05:40 -0700117 credentials = credentials.Credentials.from_authorized_user_info(
118 info, scopes=scopes
Bu Sun Kimab2be5d2020-07-15 16:49:27 -0700119 )
Danny Hermes895e3692017-11-09 11:35:57 -0800120 except ValueError as caught_exc:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700121 msg = "Failed to load authorized user credentials from {}".format(filename)
Danny Hermes0a93e872017-11-09 12:18:58 -0800122 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -0800123 six.raise_from(new_exc, caught_exc)
Bu Sun Kimab2be5d2020-07-15 16:49:27 -0700124 if quota_project_id:
125 credentials = credentials.with_quota_project(quota_project_id)
arithmetic1728f30b45a2020-06-17 23:36:04 -0700126 if not credentials.quota_project_id:
127 _warn_about_problematic_credentials(credentials)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700128 return credentials, None
129
130 elif credential_type == _SERVICE_ACCOUNT_TYPE:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800131 from google.oauth2 import service_account
132
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700133 try:
Bu Sun Kim15d5fa92020-06-18 14:05:40 -0700134 credentials = service_account.Credentials.from_service_account_info(
135 info, scopes=scopes
Bu Sun Kimab2be5d2020-07-15 16:49:27 -0700136 )
Danny Hermes895e3692017-11-09 11:35:57 -0800137 except ValueError as caught_exc:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700138 msg = "Failed to load service account credentials from {}".format(filename)
Danny Hermes0a93e872017-11-09 12:18:58 -0800139 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -0800140 six.raise_from(new_exc, caught_exc)
Bu Sun Kimab2be5d2020-07-15 16:49:27 -0700141 if quota_project_id:
142 credentials = credentials.with_quota_project(quota_project_id)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700143 return credentials, info.get("project_id")
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700144
145 else:
146 raise exceptions.DefaultCredentialsError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700147 "The file {file} does not have a valid type. "
148 "Type is {type}, expected one of {valid_types}.".format(
149 file=filename, type=credential_type, valid_types=_VALID_TYPES
150 )
151 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700152
153
154def _get_gcloud_sdk_credentials():
155 """Gets the credentials and project ID from the Cloud SDK."""
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800156 from google.auth import _cloud_sdk
157
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400158 _LOGGER.debug("Checking Cloud SDK credentials as part of auth process...")
159
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700160 # Check if application default credentials exist.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700161 credentials_filename = _cloud_sdk.get_application_default_credentials_path()
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700162
163 if not os.path.isfile(credentials_filename):
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400164 _LOGGER.debug("Cloud SDK credentials not found on disk; not using them")
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700165 return None, None
166
Bu Sun Kim15d5fa92020-06-18 14:05:40 -0700167 credentials, project_id = load_credentials_from_file(credentials_filename)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700168
169 if not project_id:
170 project_id = _cloud_sdk.get_project_id()
171
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700172 return credentials, project_id
173
174
175def _get_explicit_environ_credentials():
176 """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
177 variable."""
178 explicit_file = os.environ.get(environment_vars.CREDENTIALS)
179
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400180 _LOGGER.debug(
181 "Checking %s for explicit credentials as part of auth process...", explicit_file
182 )
183
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700184 if explicit_file is not None:
Bu Sun Kim15d5fa92020-06-18 14:05:40 -0700185 credentials, project_id = load_credentials_from_file(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700186 os.environ[environment_vars.CREDENTIALS]
187 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700188
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700189 return credentials, project_id
190
191 else:
192 return None, None
193
194
195def _get_gae_credentials():
196 """Gets Google App Engine App Identity credentials and project ID."""
James Wilson6e0781b2018-12-20 20:38:52 -0500197 # While this library is normally bundled with app_engine, there are
198 # some cases where it's not available, so we tolerate ImportError.
199 try:
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400200 _LOGGER.debug("Checking for App Engine runtime as part of auth process...")
James Wilson6e0781b2018-12-20 20:38:52 -0500201 import google.auth.app_engine as app_engine
202 except ImportError:
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400203 _LOGGER.warning("Import of App Engine auth library failed.")
James Wilson6e0781b2018-12-20 20:38:52 -0500204 return None, None
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800205
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -0700206 try:
207 credentials = app_engine.Credentials()
208 project_id = app_engine.get_project_id()
209 return credentials, project_id
210 except EnvironmentError:
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400211 _LOGGER.debug(
212 "No App Engine library was found so cannot authentication via App Engine Identity Credentials."
213 )
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -0700214 return None, None
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700215
216
217def _get_gce_credentials(request=None):
218 """Gets credentials and project ID from the GCE Metadata Service."""
219 # Ping requires a transport, but we want application default credentials
220 # to require no arguments. So, we'll use the _http_client transport which
221 # uses http.client. This is only acceptable because the metadata server
222 # doesn't do SSL and never requires proxies.
James Wilson6e0781b2018-12-20 20:38:52 -0500223
224 # While this library is normally bundled with compute_engine, there are
225 # some cases where it's not available, so we tolerate ImportError.
226 try:
227 from google.auth import compute_engine
228 from google.auth.compute_engine import _metadata
229 except ImportError:
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400230 _LOGGER.warning("Import of Compute Engine auth library failed.")
James Wilson6e0781b2018-12-20 20:38:52 -0500231 return None, None
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700232
233 if request is None:
234 request = google.auth.transport._http_client.Request()
235
236 if _metadata.ping(request=request):
237 # Get the project ID.
238 try:
Jon Wayne Parrott5b03ba12016-10-24 13:51:26 -0700239 project_id = _metadata.get_project_id(request=request)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700240 except exceptions.TransportError:
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700241 project_id = None
242
243 return compute_engine.Credentials(), project_id
244 else:
Vaughan Hiltsecd88d42020-07-21 16:25:51 -0400245 _LOGGER.warning(
246 "Authentication failed using Compute Engine authentication due to unavailable metadata server."
247 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700248 return None, None
249
250
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700251def default(scopes=None, request=None, quota_project_id=None):
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700252 """Gets the default credentials for the current environment.
253
254 `Application Default Credentials`_ provides an easy way to obtain
255 credentials to call Google APIs for server-to-server or local applications.
256 This function acquires credentials from the environment in the following
257 order:
258
259 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
260 to the path of a valid service account JSON private key file, then it is
261 loaded and returned. The project ID returned is the project ID defined
262 in the service account file if available (some older files do not
263 contain project ID information).
264 2. If the `Google Cloud SDK`_ is installed and has application default
265 credentials set they are loaded and returned.
266
267 To enable application default credentials with the Cloud SDK run::
268
269 gcloud auth application-default login
270
271 If the Cloud SDK has an active project, the project ID is returned. The
272 active project can be set using::
273
274 gcloud config set project
275
276 3. If the application is running in the `App Engine standard environment`_
277 then the credentials and project ID from the `App Identity Service`_
278 are used.
279 4. If the application is running in `Compute Engine`_ or the
280 `App Engine flexible environment`_ then the credentials and project ID
281 are obtained from the `Metadata Service`_.
282 5. If no credentials are found,
283 :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
284
285 .. _Application Default Credentials: https://developers.google.com\
286 /identity/protocols/application-default-credentials
287 .. _Google Cloud SDK: https://cloud.google.com/sdk
288 .. _App Engine standard environment: https://cloud.google.com/appengine
289 .. _App Identity Service: https://cloud.google.com/appengine/docs/python\
290 /appidentity/
291 .. _Compute Engine: https://cloud.google.com/compute
292 .. _App Engine flexible environment: https://cloud.google.com\
293 /appengine/flexible
294 .. _Metadata Service: https://cloud.google.com/compute/docs\
295 /storing-retrieving-metadata
296
297 Example::
298
299 import google.auth
300
301 credentials, project_id = google.auth.default()
302
303 Args:
Jon Wayne Parrott8a7e5062016-11-07 16:45:17 -0800304 scopes (Sequence[str]): The list of scopes for the credentials. If
305 specified, the credentials will automatically be scoped if
306 necessary.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700307 request (google.auth.transport.Request): An object used to make
308 HTTP requests. This is used to detect whether the application
309 is running on Compute Engine. If not specified, then it will
310 use the standard library http client to make requests.
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700311 quota_project_id (Optional[str]): The project ID used for
312 quota and billing.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700313 Returns:
314 Tuple[~google.auth.credentials.Credentials, Optional[str]]:
315 the current environment's credentials and project ID. Project ID
316 may be None, which indicates that the Project ID could not be
317 ascertained from the environment.
318
319 Raises:
320 ~google.auth.exceptions.DefaultCredentialsError:
321 If no credentials were found, or if the credentials found were
322 invalid.
323 """
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800324 from google.auth.credentials import with_scopes_if_required
325
Jon Wayne Parrottce37cba2016-11-07 16:41:42 -0800326 explicit_project_id = os.environ.get(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700327 environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)
328 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700329
330 checkers = (
331 _get_explicit_environ_credentials,
332 _get_gcloud_sdk_credentials,
333 _get_gae_credentials,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700334 lambda: _get_gce_credentials(request),
335 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700336
337 for checker in checkers:
338 credentials, project_id = checker()
339 if credentials is not None:
Bu Sun Kimab2be5d2020-07-15 16:49:27 -0700340 credentials = with_scopes_if_required(credentials, scopes)
341 if quota_project_id:
342 credentials = credentials.with_quota_project(quota_project_id)
343
Jacob Hayes15af07b2017-12-13 14:09:47 -0600344 effective_project_id = explicit_project_id or project_id
345 if not effective_project_id:
346 _LOGGER.warning(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700347 "No project ID could be determined. Consider running "
348 "`gcloud config set project` or setting the %s "
349 "environment variable",
350 environment_vars.PROJECT,
351 )
Jacob Hayes15af07b2017-12-13 14:09:47 -0600352 return credentials, effective_project_id
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700353
354 raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)