Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 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 | |
| 15 | """Application default credentials. |
| 16 | |
| 17 | Implements application default credentials and project ID detection. |
| 18 | """ |
| 19 | |
| 20 | import io |
| 21 | import json |
| 22 | import logging |
| 23 | import os |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame^] | 24 | import warnings |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 25 | |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 26 | import six |
| 27 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 28 | from google.auth import environment_vars |
| 29 | from google.auth import exceptions |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 30 | import google.auth.transport._http_client |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 31 | |
| 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 Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame^] | 40 | _HELP_MESSAGE = """\ |
| 41 | Could not automatically determine credentials. Please set {env} or \ |
| 42 | explicitly create credentials and re-run the application. For more \ |
| 43 | information, please see \ |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 44 | https://developers.google.com/accounts/docs/application-default-credentials. |
| 45 | """.format(env=environment_vars.CREDENTIALS).strip() |
| 46 | |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame^] | 47 | # Warning when using Cloud SDK user credentials |
| 48 | _CLOUD_SDK_CREDENTIALS_WARNING = """\ |
| 49 | Your application has authenticated using end user credentials from Google \ |
| 50 | Cloud SDK. We recommend that most server applications use service accounts \ |
| 51 | instead. If your application continues to use end user credentials from Cloud \ |
| 52 | SDK, you might receive a "quota exceeded" or "API not enabled" error. For \ |
| 53 | more information about service accounts, see \ |
| 54 | https://cloud.google.com/docs/authentication/.""" |
| 55 | |
| 56 | |
| 57 | def _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 Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 68 | |
| 69 | def _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 |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 85 | wrong format or is missing. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 86 | """ |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 87 | if not os.path.exists(filename): |
| 88 | raise exceptions.DefaultCredentialsError( |
| 89 | 'File {} was not found.'.format(filename)) |
| 90 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 91 | with io.open(filename, 'r') as file_obj: |
| 92 | try: |
| 93 | info = json.load(file_obj) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 94 | except ValueError as caught_exc: |
| 95 | new_exc = exceptions.DefaultCredentialsError( |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 96 | 'File {} is not a valid json file.'.format(filename), |
| 97 | caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 98 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 99 | |
| 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 Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 105 | from google.auth import _cloud_sdk |
| 106 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 107 | try: |
| 108 | credentials = _cloud_sdk.load_authorized_user_credentials(info) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 109 | except ValueError as caught_exc: |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 110 | msg = 'Failed to load authorized user credentials from {}'.format( |
| 111 | filename) |
| 112 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 113 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 114 | # Authorized user credentials do not contain the project ID. |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame^] | 115 | _warn_about_problematic_credentials(credentials) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 116 | return credentials, None |
| 117 | |
| 118 | elif credential_type == _SERVICE_ACCOUNT_TYPE: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 119 | from google.oauth2 import service_account |
| 120 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 121 | try: |
| 122 | credentials = ( |
| 123 | service_account.Credentials.from_service_account_info(info)) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 124 | except ValueError as caught_exc: |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 125 | msg = 'Failed to load service account credentials from {}'.format( |
| 126 | filename) |
| 127 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 128 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 129 | 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 | |
| 138 | def _get_gcloud_sdk_credentials(): |
| 139 | """Gets the credentials and project ID from the Cloud SDK.""" |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 140 | from google.auth import _cloud_sdk |
| 141 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 142 | # 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 Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 155 | return credentials, project_id |
| 156 | |
| 157 | |
| 158 | def _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 Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 167 | return credentials, project_id |
| 168 | |
| 169 | else: |
| 170 | return None, None |
| 171 | |
| 172 | |
| 173 | def _get_gae_credentials(): |
| 174 | """Gets Google App Engine App Identity credentials and project ID.""" |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 175 | from google.auth import app_engine |
| 176 | |
Jon Wayne Parrott | 2148fde | 2016-10-24 13:44:25 -0700 | [diff] [blame] | 177 | 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 Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 183 | |
| 184 | |
| 185 | def _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 Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 191 | from google.auth import compute_engine |
| 192 | from google.auth.compute_engine import _metadata |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 193 | |
| 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 Parrott | 5b03ba1 | 2016-10-24 13:51:26 -0700 | [diff] [blame] | 200 | project_id = _metadata.get_project_id(request=request) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 201 | except exceptions.TransportError: |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 202 | project_id = None |
| 203 | |
| 204 | return compute_engine.Credentials(), project_id |
| 205 | else: |
| 206 | return None, None |
| 207 | |
| 208 | |
Jon Wayne Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 209 | def default(scopes=None, request=None): |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 210 | """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 Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 262 | scopes (Sequence[str]): The list of scopes for the credentials. If |
| 263 | specified, the credentials will automatically be scoped if |
| 264 | necessary. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 265 | 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 Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 281 | from google.auth.credentials import with_scopes_if_required |
| 282 | |
Jon Wayne Parrott | ce37cba | 2016-11-07 16:41:42 -0800 | [diff] [blame] | 283 | explicit_project_id = os.environ.get( |
| 284 | environment_vars.PROJECT, |
| 285 | os.environ.get(environment_vars.LEGACY_PROJECT)) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 286 | |
| 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 Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 296 | credentials = with_scopes_if_required(credentials, scopes) |
Jacob Hayes | 15af07b | 2017-12-13 14:09:47 -0600 | [diff] [blame] | 297 | 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 Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 305 | |
| 306 | raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) |