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 |
| 24 | |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 25 | import six |
| 26 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 27 | from google.auth import environment_vars |
| 28 | from google.auth import exceptions |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 29 | import google.auth.transport._http_client |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 30 | |
| 31 | _LOGGER = logging.getLogger(__name__) |
| 32 | |
| 33 | # Valid types accepted for file-based credentials. |
| 34 | _AUTHORIZED_USER_TYPE = 'authorized_user' |
| 35 | _SERVICE_ACCOUNT_TYPE = 'service_account' |
| 36 | _VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE) |
| 37 | |
| 38 | # Help message when no credentials can be found. |
| 39 | _HELP_MESSAGE = """ |
| 40 | Could not automatically determine credentials. Please set {env} or |
| 41 | explicitly create credential and re-run the application. For more |
| 42 | information, please see |
| 43 | https://developers.google.com/accounts/docs/application-default-credentials. |
| 44 | """.format(env=environment_vars.CREDENTIALS).strip() |
| 45 | |
| 46 | |
| 47 | def _load_credentials_from_file(filename): |
| 48 | """Loads credentials from a file. |
| 49 | |
| 50 | The credentials file must be a service account key or stored authorized |
| 51 | user credentials. |
| 52 | |
| 53 | Args: |
| 54 | filename (str): The full path to the credentials file. |
| 55 | |
| 56 | Returns: |
| 57 | Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded |
| 58 | credentials and the project ID. Authorized user credentials do not |
| 59 | have the project ID information. |
| 60 | |
| 61 | Raises: |
| 62 | google.auth.exceptions.DefaultCredentialsError: if the file is in the |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 63 | wrong format or is missing. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 64 | """ |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 65 | if not os.path.exists(filename): |
| 66 | raise exceptions.DefaultCredentialsError( |
| 67 | 'File {} was not found.'.format(filename)) |
| 68 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 69 | with io.open(filename, 'r') as file_obj: |
| 70 | try: |
| 71 | info = json.load(file_obj) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 72 | except ValueError as caught_exc: |
| 73 | new_exc = exceptions.DefaultCredentialsError( |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 74 | 'File {} is not a valid json file.'.format(filename), |
| 75 | caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 76 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 77 | |
| 78 | # The type key should indicate that the file is either a service account |
| 79 | # credentials file or an authorized user credentials file. |
| 80 | credential_type = info.get('type') |
| 81 | |
| 82 | if credential_type == _AUTHORIZED_USER_TYPE: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 83 | from google.auth import _cloud_sdk |
| 84 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 85 | try: |
| 86 | credentials = _cloud_sdk.load_authorized_user_credentials(info) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 87 | except ValueError as caught_exc: |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 88 | msg = 'Failed to load authorized user credentials from {}'.format( |
| 89 | filename) |
| 90 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 91 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 92 | # Authorized user credentials do not contain the project ID. |
| 93 | return credentials, None |
| 94 | |
| 95 | elif credential_type == _SERVICE_ACCOUNT_TYPE: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 96 | from google.oauth2 import service_account |
| 97 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 98 | try: |
| 99 | credentials = ( |
| 100 | service_account.Credentials.from_service_account_info(info)) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 101 | except ValueError as caught_exc: |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 102 | msg = 'Failed to load service account credentials from {}'.format( |
| 103 | filename) |
| 104 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 105 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 106 | return credentials, info.get('project_id') |
| 107 | |
| 108 | else: |
| 109 | raise exceptions.DefaultCredentialsError( |
| 110 | 'The file {file} does not have a valid type. ' |
| 111 | 'Type is {type}, expected one of {valid_types}.'.format( |
| 112 | file=filename, type=credential_type, valid_types=_VALID_TYPES)) |
| 113 | |
| 114 | |
| 115 | def _get_gcloud_sdk_credentials(): |
| 116 | """Gets the credentials and project ID from the Cloud SDK.""" |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 117 | from google.auth import _cloud_sdk |
| 118 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 119 | # Check if application default credentials exist. |
| 120 | credentials_filename = ( |
| 121 | _cloud_sdk.get_application_default_credentials_path()) |
| 122 | |
| 123 | if not os.path.isfile(credentials_filename): |
| 124 | return None, None |
| 125 | |
| 126 | credentials, project_id = _load_credentials_from_file( |
| 127 | credentials_filename) |
| 128 | |
| 129 | if not project_id: |
| 130 | project_id = _cloud_sdk.get_project_id() |
| 131 | |
| 132 | if not project_id: |
| 133 | _LOGGER.warning( |
| 134 | 'No project ID could be determined from the Cloud SDK ' |
| 135 | 'configuration. Consider running `gcloud config set project` or ' |
| 136 | 'setting the %s environment variable', environment_vars.PROJECT) |
| 137 | |
| 138 | return credentials, project_id |
| 139 | |
| 140 | |
| 141 | def _get_explicit_environ_credentials(): |
| 142 | """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment |
| 143 | variable.""" |
| 144 | explicit_file = os.environ.get(environment_vars.CREDENTIALS) |
| 145 | |
| 146 | if explicit_file is not None: |
| 147 | credentials, project_id = _load_credentials_from_file( |
| 148 | os.environ[environment_vars.CREDENTIALS]) |
| 149 | |
| 150 | if not project_id: |
| 151 | _LOGGER.warning( |
| 152 | 'No project ID could be determined from the credentials at %s ' |
| 153 | 'Consider setting the %s environment variable', |
| 154 | environment_vars.CREDENTIALS, environment_vars.PROJECT) |
| 155 | |
| 156 | return credentials, project_id |
| 157 | |
| 158 | else: |
| 159 | return None, None |
| 160 | |
| 161 | |
| 162 | def _get_gae_credentials(): |
| 163 | """Gets Google App Engine App Identity credentials and project ID.""" |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 164 | from google.auth import app_engine |
| 165 | |
Jon Wayne Parrott | 2148fde | 2016-10-24 13:44:25 -0700 | [diff] [blame] | 166 | try: |
| 167 | credentials = app_engine.Credentials() |
| 168 | project_id = app_engine.get_project_id() |
| 169 | return credentials, project_id |
| 170 | except EnvironmentError: |
| 171 | return None, None |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 172 | |
| 173 | |
| 174 | def _get_gce_credentials(request=None): |
| 175 | """Gets credentials and project ID from the GCE Metadata Service.""" |
| 176 | # Ping requires a transport, but we want application default credentials |
| 177 | # to require no arguments. So, we'll use the _http_client transport which |
| 178 | # uses http.client. This is only acceptable because the metadata server |
| 179 | # doesn't do SSL and never requires proxies. |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 180 | from google.auth import compute_engine |
| 181 | from google.auth.compute_engine import _metadata |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 182 | |
| 183 | if request is None: |
| 184 | request = google.auth.transport._http_client.Request() |
| 185 | |
| 186 | if _metadata.ping(request=request): |
| 187 | # Get the project ID. |
| 188 | try: |
Jon Wayne Parrott | 5b03ba1 | 2016-10-24 13:51:26 -0700 | [diff] [blame] | 189 | project_id = _metadata.get_project_id(request=request) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 190 | except exceptions.TransportError: |
| 191 | _LOGGER.warning( |
| 192 | 'No project ID could be determined from the Compute Engine ' |
| 193 | 'metadata service. Consider setting the %s environment ' |
| 194 | 'variable.', environment_vars.PROJECT) |
| 195 | project_id = None |
| 196 | |
| 197 | return compute_engine.Credentials(), project_id |
| 198 | else: |
| 199 | return None, None |
| 200 | |
| 201 | |
Jon Wayne Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 202 | def default(scopes=None, request=None): |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 203 | """Gets the default credentials for the current environment. |
| 204 | |
| 205 | `Application Default Credentials`_ provides an easy way to obtain |
| 206 | credentials to call Google APIs for server-to-server or local applications. |
| 207 | This function acquires credentials from the environment in the following |
| 208 | order: |
| 209 | |
| 210 | 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set |
| 211 | to the path of a valid service account JSON private key file, then it is |
| 212 | loaded and returned. The project ID returned is the project ID defined |
| 213 | in the service account file if available (some older files do not |
| 214 | contain project ID information). |
| 215 | 2. If the `Google Cloud SDK`_ is installed and has application default |
| 216 | credentials set they are loaded and returned. |
| 217 | |
| 218 | To enable application default credentials with the Cloud SDK run:: |
| 219 | |
| 220 | gcloud auth application-default login |
| 221 | |
| 222 | If the Cloud SDK has an active project, the project ID is returned. The |
| 223 | active project can be set using:: |
| 224 | |
| 225 | gcloud config set project |
| 226 | |
| 227 | 3. If the application is running in the `App Engine standard environment`_ |
| 228 | then the credentials and project ID from the `App Identity Service`_ |
| 229 | are used. |
| 230 | 4. If the application is running in `Compute Engine`_ or the |
| 231 | `App Engine flexible environment`_ then the credentials and project ID |
| 232 | are obtained from the `Metadata Service`_. |
| 233 | 5. If no credentials are found, |
| 234 | :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. |
| 235 | |
| 236 | .. _Application Default Credentials: https://developers.google.com\ |
| 237 | /identity/protocols/application-default-credentials |
| 238 | .. _Google Cloud SDK: https://cloud.google.com/sdk |
| 239 | .. _App Engine standard environment: https://cloud.google.com/appengine |
| 240 | .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ |
| 241 | /appidentity/ |
| 242 | .. _Compute Engine: https://cloud.google.com/compute |
| 243 | .. _App Engine flexible environment: https://cloud.google.com\ |
| 244 | /appengine/flexible |
| 245 | .. _Metadata Service: https://cloud.google.com/compute/docs\ |
| 246 | /storing-retrieving-metadata |
| 247 | |
| 248 | Example:: |
| 249 | |
| 250 | import google.auth |
| 251 | |
| 252 | credentials, project_id = google.auth.default() |
| 253 | |
| 254 | Args: |
Jon Wayne Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 255 | scopes (Sequence[str]): The list of scopes for the credentials. If |
| 256 | specified, the credentials will automatically be scoped if |
| 257 | necessary. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 258 | request (google.auth.transport.Request): An object used to make |
| 259 | HTTP requests. This is used to detect whether the application |
| 260 | is running on Compute Engine. If not specified, then it will |
| 261 | use the standard library http client to make requests. |
| 262 | |
| 263 | Returns: |
| 264 | Tuple[~google.auth.credentials.Credentials, Optional[str]]: |
| 265 | the current environment's credentials and project ID. Project ID |
| 266 | may be None, which indicates that the Project ID could not be |
| 267 | ascertained from the environment. |
| 268 | |
| 269 | Raises: |
| 270 | ~google.auth.exceptions.DefaultCredentialsError: |
| 271 | If no credentials were found, or if the credentials found were |
| 272 | invalid. |
| 273 | """ |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 274 | from google.auth.credentials import with_scopes_if_required |
| 275 | |
Jon Wayne Parrott | ce37cba | 2016-11-07 16:41:42 -0800 | [diff] [blame] | 276 | explicit_project_id = os.environ.get( |
| 277 | environment_vars.PROJECT, |
| 278 | os.environ.get(environment_vars.LEGACY_PROJECT)) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 279 | |
| 280 | checkers = ( |
| 281 | _get_explicit_environ_credentials, |
| 282 | _get_gcloud_sdk_credentials, |
| 283 | _get_gae_credentials, |
| 284 | lambda: _get_gce_credentials(request)) |
| 285 | |
| 286 | for checker in checkers: |
| 287 | credentials, project_id = checker() |
| 288 | if credentials is not None: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 289 | credentials = with_scopes_if_required(credentials, scopes) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 290 | return credentials, explicit_project_id or project_id |
| 291 | |
| 292 | raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) |