blob: 32e81ba5faa443e07dd9a8ecf43b3c73d5307556 [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 \
52Cloud SDK. We recommend that most server applications use service accounts \
53instead. If your application continues to use end user credentials from Cloud \
54SDK, you might receive a "quota exceeded" or "API not enabled" error. For \
55more information about service accounts, see \
Jeffrey Sorensen62cfc6d2018-08-13 16:39:06 -040056https://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
72def _load_credentials_from_file(filename):
73 """Loads credentials from a file.
74
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.
80
81 Returns:
82 Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
83 credentials and the project ID. Authorized user credentials do not
84 have the project ID information.
85
86 Raises:
87 google.auth.exceptions.DefaultCredentialsError: if the file is in the
weitaiting6e86c932017-08-12 03:26:59 +080088 wrong format or is missing.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070089 """
weitaiting6e86c932017-08-12 03:26:59 +080090 if not os.path.exists(filename):
91 raise exceptions.DefaultCredentialsError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -070092 "File {} was not found.".format(filename)
93 )
weitaiting6e86c932017-08-12 03:26:59 +080094
Bu Sun Kim9eec0912019-10-21 17:04:21 -070095 with io.open(filename, "r") as file_obj:
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070096 try:
97 info = json.load(file_obj)
Danny Hermes895e3692017-11-09 11:35:57 -080098 except ValueError as caught_exc:
99 new_exc = exceptions.DefaultCredentialsError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700100 "File {} is not a valid json file.".format(filename), caught_exc
101 )
Danny Hermes895e3692017-11-09 11:35:57 -0800102 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700103
104 # The type key should indicate that the file is either a service account
105 # credentials file or an authorized user credentials file.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700106 credential_type = info.get("type")
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700107
108 if credential_type == _AUTHORIZED_USER_TYPE:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800109 from google.auth import _cloud_sdk
110
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700111 try:
112 credentials = _cloud_sdk.load_authorized_user_credentials(info)
Danny Hermes895e3692017-11-09 11:35:57 -0800113 except ValueError as caught_exc:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700114 msg = "Failed to load authorized user credentials from {}".format(filename)
Danny Hermes0a93e872017-11-09 12:18:58 -0800115 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -0800116 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700117 # Authorized user credentials do not contain the project ID.
Thea Flowersa8d93482018-05-31 14:52:06 -0700118 _warn_about_problematic_credentials(credentials)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700119 return credentials, None
120
121 elif credential_type == _SERVICE_ACCOUNT_TYPE:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800122 from google.oauth2 import service_account
123
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700124 try:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700125 credentials = service_account.Credentials.from_service_account_info(info)
Danny Hermes895e3692017-11-09 11:35:57 -0800126 except ValueError as caught_exc:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700127 msg = "Failed to load service account credentials from {}".format(filename)
Danny Hermes0a93e872017-11-09 12:18:58 -0800128 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -0800129 six.raise_from(new_exc, caught_exc)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700130 return credentials, info.get("project_id")
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700131
132 else:
133 raise exceptions.DefaultCredentialsError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700134 "The file {file} does not have a valid type. "
135 "Type is {type}, expected one of {valid_types}.".format(
136 file=filename, type=credential_type, valid_types=_VALID_TYPES
137 )
138 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700139
140
141def _get_gcloud_sdk_credentials():
142 """Gets the credentials and project ID from the Cloud SDK."""
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800143 from google.auth import _cloud_sdk
144
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700145 # Check if application default credentials exist.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700146 credentials_filename = _cloud_sdk.get_application_default_credentials_path()
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700147
148 if not os.path.isfile(credentials_filename):
149 return None, None
150
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700151 credentials, project_id = _load_credentials_from_file(credentials_filename)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700152
153 if not project_id:
154 project_id = _cloud_sdk.get_project_id()
155
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700156 return credentials, project_id
157
158
159def _get_explicit_environ_credentials():
160 """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
161 variable."""
162 explicit_file = os.environ.get(environment_vars.CREDENTIALS)
163
164 if explicit_file is not None:
165 credentials, project_id = _load_credentials_from_file(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700166 os.environ[environment_vars.CREDENTIALS]
167 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700168
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700169 return credentials, project_id
170
171 else:
172 return None, None
173
174
175def _get_gae_credentials():
176 """Gets Google App Engine App Identity credentials and project ID."""
James Wilson6e0781b2018-12-20 20:38:52 -0500177 # While this library is normally bundled with app_engine, there are
178 # some cases where it's not available, so we tolerate ImportError.
179 try:
180 import google.auth.app_engine as app_engine
181 except ImportError:
182 return None, None
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800183
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -0700184 try:
185 credentials = app_engine.Credentials()
186 project_id = app_engine.get_project_id()
187 return credentials, project_id
188 except EnvironmentError:
189 return None, None
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700190
191
192def _get_gce_credentials(request=None):
193 """Gets credentials and project ID from the GCE Metadata Service."""
194 # Ping requires a transport, but we want application default credentials
195 # to require no arguments. So, we'll use the _http_client transport which
196 # uses http.client. This is only acceptable because the metadata server
197 # doesn't do SSL and never requires proxies.
James Wilson6e0781b2018-12-20 20:38:52 -0500198
199 # While this library is normally bundled with compute_engine, there are
200 # some cases where it's not available, so we tolerate ImportError.
201 try:
202 from google.auth import compute_engine
203 from google.auth.compute_engine import _metadata
204 except ImportError:
205 return None, None
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700206
207 if request is None:
208 request = google.auth.transport._http_client.Request()
209
210 if _metadata.ping(request=request):
211 # Get the project ID.
212 try:
Jon Wayne Parrott5b03ba12016-10-24 13:51:26 -0700213 project_id = _metadata.get_project_id(request=request)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700214 except exceptions.TransportError:
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700215 project_id = None
216
217 return compute_engine.Credentials(), project_id
218 else:
219 return None, None
220
221
Jon Wayne Parrott8a7e5062016-11-07 16:45:17 -0800222def default(scopes=None, request=None):
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700223 """Gets the default credentials for the current environment.
224
225 `Application Default Credentials`_ provides an easy way to obtain
226 credentials to call Google APIs for server-to-server or local applications.
227 This function acquires credentials from the environment in the following
228 order:
229
230 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
231 to the path of a valid service account JSON private key file, then it is
232 loaded and returned. The project ID returned is the project ID defined
233 in the service account file if available (some older files do not
234 contain project ID information).
235 2. If the `Google Cloud SDK`_ is installed and has application default
236 credentials set they are loaded and returned.
237
238 To enable application default credentials with the Cloud SDK run::
239
240 gcloud auth application-default login
241
242 If the Cloud SDK has an active project, the project ID is returned. The
243 active project can be set using::
244
245 gcloud config set project
246
247 3. If the application is running in the `App Engine standard environment`_
248 then the credentials and project ID from the `App Identity Service`_
249 are used.
250 4. If the application is running in `Compute Engine`_ or the
251 `App Engine flexible environment`_ then the credentials and project ID
252 are obtained from the `Metadata Service`_.
253 5. If no credentials are found,
254 :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
255
256 .. _Application Default Credentials: https://developers.google.com\
257 /identity/protocols/application-default-credentials
258 .. _Google Cloud SDK: https://cloud.google.com/sdk
259 .. _App Engine standard environment: https://cloud.google.com/appengine
260 .. _App Identity Service: https://cloud.google.com/appengine/docs/python\
261 /appidentity/
262 .. _Compute Engine: https://cloud.google.com/compute
263 .. _App Engine flexible environment: https://cloud.google.com\
264 /appengine/flexible
265 .. _Metadata Service: https://cloud.google.com/compute/docs\
266 /storing-retrieving-metadata
267
268 Example::
269
270 import google.auth
271
272 credentials, project_id = google.auth.default()
273
274 Args:
Jon Wayne Parrott8a7e5062016-11-07 16:45:17 -0800275 scopes (Sequence[str]): The list of scopes for the credentials. If
276 specified, the credentials will automatically be scoped if
277 necessary.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700278 request (google.auth.transport.Request): An object used to make
279 HTTP requests. This is used to detect whether the application
280 is running on Compute Engine. If not specified, then it will
281 use the standard library http client to make requests.
282
283 Returns:
284 Tuple[~google.auth.credentials.Credentials, Optional[str]]:
285 the current environment's credentials and project ID. Project ID
286 may be None, which indicates that the Project ID could not be
287 ascertained from the environment.
288
289 Raises:
290 ~google.auth.exceptions.DefaultCredentialsError:
291 If no credentials were found, or if the credentials found were
292 invalid.
293 """
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800294 from google.auth.credentials import with_scopes_if_required
295
Jon Wayne Parrottce37cba2016-11-07 16:41:42 -0800296 explicit_project_id = os.environ.get(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700297 environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)
298 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700299
300 checkers = (
301 _get_explicit_environ_credentials,
302 _get_gcloud_sdk_credentials,
303 _get_gae_credentials,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700304 lambda: _get_gce_credentials(request),
305 )
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700306
307 for checker in checkers:
308 credentials, project_id = checker()
309 if credentials is not None:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800310 credentials = with_scopes_if_required(credentials, scopes)
Jacob Hayes15af07b2017-12-13 14:09:47 -0600311 effective_project_id = explicit_project_id or project_id
312 if not effective_project_id:
313 _LOGGER.warning(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700314 "No project ID could be determined. Consider running "
315 "`gcloud config set project` or setting the %s "
316 "environment variable",
317 environment_vars.PROJECT,
318 )
Jacob Hayes15af07b2017-12-13 14:09:47 -0600319 return credentials, effective_project_id
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700320
321 raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)