blob: c93b4896326351ffd6f519422669960e78005f0f [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.
35_AUTHORIZED_USER_TYPE = 'authorized_user'
36_SERVICE_ACCOUNT_TYPE = 'service_account'
37_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
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070045""".format(env=environment_vars.CREDENTIALS).strip()
46
Thea Flowersa8d93482018-05-31 14:52:06 -070047# Warning when using Cloud SDK user credentials
48_CLOUD_SDK_CREDENTIALS_WARNING = """\
49Your application has authenticated using end user credentials from Google \
50Cloud SDK. We recommend that most server applications use service accounts \
51instead. If your application continues to use end user credentials from Cloud \
52SDK, you might receive a "quota exceeded" or "API not enabled" error. For \
53more information about service accounts, see \
Jeffrey Sorensen62cfc6d2018-08-13 16:39:06 -040054https://cloud.google.com/docs/authentication/"""
Thea Flowersa8d93482018-05-31 14:52:06 -070055
56
57def _warn_about_problematic_credentials(credentials):
58 """Determines if the credentials are problematic.
59
60 Credentials from the Cloud SDK that are associated with Cloud SDK's project
61 are problematic because they may not have APIs enabled and have limited
62 quota. If this is the case, warn about it.
63 """
64 from google.auth import _cloud_sdk
65 if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:
66 warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)
67
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070068
69def _load_credentials_from_file(filename):
70 """Loads credentials from a file.
71
72 The credentials file must be a service account key or stored authorized
73 user credentials.
74
75 Args:
76 filename (str): The full path to the credentials file.
77
78 Returns:
79 Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
80 credentials and the project ID. Authorized user credentials do not
81 have the project ID information.
82
83 Raises:
84 google.auth.exceptions.DefaultCredentialsError: if the file is in the
weitaiting6e86c932017-08-12 03:26:59 +080085 wrong format or is missing.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070086 """
weitaiting6e86c932017-08-12 03:26:59 +080087 if not os.path.exists(filename):
88 raise exceptions.DefaultCredentialsError(
89 'File {} was not found.'.format(filename))
90
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070091 with io.open(filename, 'r') as file_obj:
92 try:
93 info = json.load(file_obj)
Danny Hermes895e3692017-11-09 11:35:57 -080094 except ValueError as caught_exc:
95 new_exc = exceptions.DefaultCredentialsError(
Danny Hermes0a93e872017-11-09 12:18:58 -080096 'File {} is not a valid json file.'.format(filename),
97 caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -080098 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070099
100 # The type key should indicate that the file is either a service account
101 # credentials file or an authorized user credentials file.
102 credential_type = info.get('type')
103
104 if credential_type == _AUTHORIZED_USER_TYPE:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800105 from google.auth import _cloud_sdk
106
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700107 try:
108 credentials = _cloud_sdk.load_authorized_user_credentials(info)
Danny Hermes895e3692017-11-09 11:35:57 -0800109 except ValueError as caught_exc:
Danny Hermes0a93e872017-11-09 12:18:58 -0800110 msg = 'Failed to load authorized user credentials from {}'.format(
111 filename)
112 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -0800113 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700114 # Authorized user credentials do not contain the project ID.
Thea Flowersa8d93482018-05-31 14:52:06 -0700115 _warn_about_problematic_credentials(credentials)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700116 return credentials, None
117
118 elif credential_type == _SERVICE_ACCOUNT_TYPE:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800119 from google.oauth2 import service_account
120
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700121 try:
122 credentials = (
123 service_account.Credentials.from_service_account_info(info))
Danny Hermes895e3692017-11-09 11:35:57 -0800124 except ValueError as caught_exc:
Danny Hermes0a93e872017-11-09 12:18:58 -0800125 msg = 'Failed to load service account credentials from {}'.format(
126 filename)
127 new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
Danny Hermes895e3692017-11-09 11:35:57 -0800128 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700129 return credentials, info.get('project_id')
130
131 else:
132 raise exceptions.DefaultCredentialsError(
133 'The file {file} does not have a valid type. '
134 'Type is {type}, expected one of {valid_types}.'.format(
135 file=filename, type=credential_type, valid_types=_VALID_TYPES))
136
137
138def _get_gcloud_sdk_credentials():
139 """Gets the credentials and project ID from the Cloud SDK."""
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800140 from google.auth import _cloud_sdk
141
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700142 # Check if application default credentials exist.
143 credentials_filename = (
144 _cloud_sdk.get_application_default_credentials_path())
145
146 if not os.path.isfile(credentials_filename):
147 return None, None
148
149 credentials, project_id = _load_credentials_from_file(
150 credentials_filename)
151
152 if not project_id:
153 project_id = _cloud_sdk.get_project_id()
154
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700155 return credentials, project_id
156
157
158def _get_explicit_environ_credentials():
159 """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
160 variable."""
161 explicit_file = os.environ.get(environment_vars.CREDENTIALS)
162
163 if explicit_file is not None:
164 credentials, project_id = _load_credentials_from_file(
165 os.environ[environment_vars.CREDENTIALS])
166
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700167 return credentials, project_id
168
169 else:
170 return None, None
171
172
173def _get_gae_credentials():
174 """Gets Google App Engine App Identity credentials and project ID."""
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800175 from google.auth import app_engine
176
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -0700177 try:
178 credentials = app_engine.Credentials()
179 project_id = app_engine.get_project_id()
180 return credentials, project_id
181 except EnvironmentError:
182 return None, None
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700183
184
185def _get_gce_credentials(request=None):
186 """Gets credentials and project ID from the GCE Metadata Service."""
187 # Ping requires a transport, but we want application default credentials
188 # to require no arguments. So, we'll use the _http_client transport which
189 # uses http.client. This is only acceptable because the metadata server
190 # doesn't do SSL and never requires proxies.
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800191 from google.auth import compute_engine
192 from google.auth.compute_engine import _metadata
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700193
194 if request is None:
195 request = google.auth.transport._http_client.Request()
196
197 if _metadata.ping(request=request):
198 # Get the project ID.
199 try:
Jon Wayne Parrott5b03ba12016-10-24 13:51:26 -0700200 project_id = _metadata.get_project_id(request=request)
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700201 except exceptions.TransportError:
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700202 project_id = None
203
204 return compute_engine.Credentials(), project_id
205 else:
206 return None, None
207
208
Jon Wayne Parrott8a7e5062016-11-07 16:45:17 -0800209def default(scopes=None, request=None):
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700210 """Gets the default credentials for the current environment.
211
212 `Application Default Credentials`_ provides an easy way to obtain
213 credentials to call Google APIs for server-to-server or local applications.
214 This function acquires credentials from the environment in the following
215 order:
216
217 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
218 to the path of a valid service account JSON private key file, then it is
219 loaded and returned. The project ID returned is the project ID defined
220 in the service account file if available (some older files do not
221 contain project ID information).
222 2. If the `Google Cloud SDK`_ is installed and has application default
223 credentials set they are loaded and returned.
224
225 To enable application default credentials with the Cloud SDK run::
226
227 gcloud auth application-default login
228
229 If the Cloud SDK has an active project, the project ID is returned. The
230 active project can be set using::
231
232 gcloud config set project
233
234 3. If the application is running in the `App Engine standard environment`_
235 then the credentials and project ID from the `App Identity Service`_
236 are used.
237 4. If the application is running in `Compute Engine`_ or the
238 `App Engine flexible environment`_ then the credentials and project ID
239 are obtained from the `Metadata Service`_.
240 5. If no credentials are found,
241 :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
242
243 .. _Application Default Credentials: https://developers.google.com\
244 /identity/protocols/application-default-credentials
245 .. _Google Cloud SDK: https://cloud.google.com/sdk
246 .. _App Engine standard environment: https://cloud.google.com/appengine
247 .. _App Identity Service: https://cloud.google.com/appengine/docs/python\
248 /appidentity/
249 .. _Compute Engine: https://cloud.google.com/compute
250 .. _App Engine flexible environment: https://cloud.google.com\
251 /appengine/flexible
252 .. _Metadata Service: https://cloud.google.com/compute/docs\
253 /storing-retrieving-metadata
254
255 Example::
256
257 import google.auth
258
259 credentials, project_id = google.auth.default()
260
261 Args:
Jon Wayne Parrott8a7e5062016-11-07 16:45:17 -0800262 scopes (Sequence[str]): The list of scopes for the credentials. If
263 specified, the credentials will automatically be scoped if
264 necessary.
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700265 request (google.auth.transport.Request): An object used to make
266 HTTP requests. This is used to detect whether the application
267 is running on Compute Engine. If not specified, then it will
268 use the standard library http client to make requests.
269
270 Returns:
271 Tuple[~google.auth.credentials.Credentials, Optional[str]]:
272 the current environment's credentials and project ID. Project ID
273 may be None, which indicates that the Project ID could not be
274 ascertained from the environment.
275
276 Raises:
277 ~google.auth.exceptions.DefaultCredentialsError:
278 If no credentials were found, or if the credentials found were
279 invalid.
280 """
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800281 from google.auth.credentials import with_scopes_if_required
282
Jon Wayne Parrottce37cba2016-11-07 16:41:42 -0800283 explicit_project_id = os.environ.get(
284 environment_vars.PROJECT,
285 os.environ.get(environment_vars.LEGACY_PROJECT))
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700286
287 checkers = (
288 _get_explicit_environ_credentials,
289 _get_gcloud_sdk_credentials,
290 _get_gae_credentials,
291 lambda: _get_gce_credentials(request))
292
293 for checker in checkers:
294 credentials, project_id = checker()
295 if credentials is not None:
Jon Wayne Parrott6dca98c2016-12-01 15:34:59 -0800296 credentials = with_scopes_if_required(credentials, scopes)
Jacob Hayes15af07b2017-12-13 14:09:47 -0600297 effective_project_id = explicit_project_id or project_id
298 if not effective_project_id:
299 _LOGGER.warning(
300 'No project ID could be determined. Consider running '
301 '`gcloud config set project` or setting the %s '
302 'environment variable',
303 environment_vars.PROJECT)
304 return credentials, effective_project_id
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700305
306 raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)