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. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 35 | _AUTHORIZED_USER_TYPE = "authorized_user" |
| 36 | _SERVICE_ACCOUNT_TYPE = "service_account" |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 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 \ |
Christopher Wilcox | f102825 | 2018-09-21 10:03:04 -0700 | [diff] [blame] | 44 | https://cloud.google.com/docs/authentication/getting-started |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 45 | """.format( |
| 46 | env=environment_vars.CREDENTIALS |
| 47 | ).strip() |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 48 | |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 49 | # Warning when using Cloud SDK user credentials |
| 50 | _CLOUD_SDK_CREDENTIALS_WARNING = """\ |
| 51 | Your application has authenticated using end user credentials from Google \ |
arithmetic1728 | f30b45a | 2020-06-17 23:36:04 -0700 | [diff] [blame] | 52 | Cloud SDK without a quota project. You might receive a "quota exceeded" \ |
| 53 | or "API not enabled" error. We recommend you rerun \ |
| 54 | `gcloud auth application-default login` and make sure a quota project is \ |
| 55 | added. Or you can use service accounts instead. For more information \ |
| 56 | about service accounts, see https://cloud.google.com/docs/authentication/""" |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 57 | |
| 58 | |
| 59 | def _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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 67 | |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 68 | if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID: |
| 69 | warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING) |
| 70 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 71 | |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame^] | 72 | def load_credentials_from_file(filename, scopes=None): |
| 73 | """Loads Google credentials from a file. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 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. |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame^] | 80 | scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If |
| 81 | specified, the credentials will automatically be scoped if |
| 82 | necessary. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 83 | |
| 84 | Returns: |
| 85 | Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded |
| 86 | credentials and the project ID. Authorized user credentials do not |
| 87 | have the project ID information. |
| 88 | |
| 89 | Raises: |
| 90 | google.auth.exceptions.DefaultCredentialsError: if the file is in the |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 91 | wrong format or is missing. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 92 | """ |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 93 | if not os.path.exists(filename): |
| 94 | raise exceptions.DefaultCredentialsError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 95 | "File {} was not found.".format(filename) |
| 96 | ) |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 97 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 98 | with io.open(filename, "r") as file_obj: |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 99 | try: |
| 100 | info = json.load(file_obj) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 101 | except ValueError as caught_exc: |
| 102 | new_exc = exceptions.DefaultCredentialsError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 103 | "File {} is not a valid json file.".format(filename), caught_exc |
| 104 | ) |
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 | |
| 107 | # The type key should indicate that the file is either a service account |
| 108 | # credentials file or an authorized user credentials file. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 109 | credential_type = info.get("type") |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 110 | |
| 111 | if credential_type == _AUTHORIZED_USER_TYPE: |
arithmetic1728 | 772dac6 | 2020-03-27 14:34:13 -0700 | [diff] [blame] | 112 | from google.oauth2 import credentials |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 113 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 114 | try: |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame^] | 115 | credentials = credentials.Credentials.from_authorized_user_info( |
| 116 | info, scopes=scopes |
| 117 | ) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 118 | except ValueError as caught_exc: |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 119 | msg = "Failed to load authorized user credentials from {}".format(filename) |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 120 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 121 | six.raise_from(new_exc, caught_exc) |
arithmetic1728 | f30b45a | 2020-06-17 23:36:04 -0700 | [diff] [blame] | 122 | if not credentials.quota_project_id: |
| 123 | _warn_about_problematic_credentials(credentials) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 124 | return credentials, None |
| 125 | |
| 126 | elif credential_type == _SERVICE_ACCOUNT_TYPE: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 127 | from google.oauth2 import service_account |
| 128 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 129 | try: |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame^] | 130 | credentials = service_account.Credentials.from_service_account_info( |
| 131 | info, scopes=scopes |
| 132 | ) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 133 | except ValueError as caught_exc: |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 134 | msg = "Failed to load service account credentials from {}".format(filename) |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 135 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 136 | six.raise_from(new_exc, caught_exc) |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 137 | return credentials, info.get("project_id") |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 138 | |
| 139 | else: |
| 140 | raise exceptions.DefaultCredentialsError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 141 | "The file {file} does not have a valid type. " |
| 142 | "Type is {type}, expected one of {valid_types}.".format( |
| 143 | file=filename, type=credential_type, valid_types=_VALID_TYPES |
| 144 | ) |
| 145 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 146 | |
| 147 | |
| 148 | def _get_gcloud_sdk_credentials(): |
| 149 | """Gets the credentials and project ID from the Cloud SDK.""" |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 150 | from google.auth import _cloud_sdk |
| 151 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 152 | # Check if application default credentials exist. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 153 | credentials_filename = _cloud_sdk.get_application_default_credentials_path() |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 154 | |
| 155 | if not os.path.isfile(credentials_filename): |
| 156 | return None, None |
| 157 | |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame^] | 158 | credentials, project_id = load_credentials_from_file(credentials_filename) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 159 | |
| 160 | if not project_id: |
| 161 | project_id = _cloud_sdk.get_project_id() |
| 162 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 163 | return credentials, project_id |
| 164 | |
| 165 | |
| 166 | def _get_explicit_environ_credentials(): |
| 167 | """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment |
| 168 | variable.""" |
| 169 | explicit_file = os.environ.get(environment_vars.CREDENTIALS) |
| 170 | |
| 171 | if explicit_file is not None: |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame^] | 172 | credentials, project_id = load_credentials_from_file( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 173 | os.environ[environment_vars.CREDENTIALS] |
| 174 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 175 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 176 | return credentials, project_id |
| 177 | |
| 178 | else: |
| 179 | return None, None |
| 180 | |
| 181 | |
| 182 | def _get_gae_credentials(): |
| 183 | """Gets Google App Engine App Identity credentials and project ID.""" |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 184 | # While this library is normally bundled with app_engine, there are |
| 185 | # some cases where it's not available, so we tolerate ImportError. |
| 186 | try: |
| 187 | import google.auth.app_engine as app_engine |
| 188 | except ImportError: |
| 189 | return None, None |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 190 | |
Jon Wayne Parrott | 2148fde | 2016-10-24 13:44:25 -0700 | [diff] [blame] | 191 | try: |
| 192 | credentials = app_engine.Credentials() |
| 193 | project_id = app_engine.get_project_id() |
| 194 | return credentials, project_id |
| 195 | except EnvironmentError: |
| 196 | return None, None |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 197 | |
| 198 | |
| 199 | def _get_gce_credentials(request=None): |
| 200 | """Gets credentials and project ID from the GCE Metadata Service.""" |
| 201 | # Ping requires a transport, but we want application default credentials |
| 202 | # to require no arguments. So, we'll use the _http_client transport which |
| 203 | # uses http.client. This is only acceptable because the metadata server |
| 204 | # doesn't do SSL and never requires proxies. |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 205 | |
| 206 | # While this library is normally bundled with compute_engine, there are |
| 207 | # some cases where it's not available, so we tolerate ImportError. |
| 208 | try: |
| 209 | from google.auth import compute_engine |
| 210 | from google.auth.compute_engine import _metadata |
| 211 | except ImportError: |
| 212 | return None, None |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 213 | |
| 214 | if request is None: |
| 215 | request = google.auth.transport._http_client.Request() |
| 216 | |
| 217 | if _metadata.ping(request=request): |
| 218 | # Get the project ID. |
| 219 | try: |
Jon Wayne Parrott | 5b03ba1 | 2016-10-24 13:51:26 -0700 | [diff] [blame] | 220 | project_id = _metadata.get_project_id(request=request) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 221 | except exceptions.TransportError: |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 222 | project_id = None |
| 223 | |
| 224 | return compute_engine.Credentials(), project_id |
| 225 | else: |
| 226 | return None, None |
| 227 | |
| 228 | |
Jon Wayne Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 229 | def default(scopes=None, request=None): |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 230 | """Gets the default credentials for the current environment. |
| 231 | |
| 232 | `Application Default Credentials`_ provides an easy way to obtain |
| 233 | credentials to call Google APIs for server-to-server or local applications. |
| 234 | This function acquires credentials from the environment in the following |
| 235 | order: |
| 236 | |
| 237 | 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set |
| 238 | to the path of a valid service account JSON private key file, then it is |
| 239 | loaded and returned. The project ID returned is the project ID defined |
| 240 | in the service account file if available (some older files do not |
| 241 | contain project ID information). |
| 242 | 2. If the `Google Cloud SDK`_ is installed and has application default |
| 243 | credentials set they are loaded and returned. |
| 244 | |
| 245 | To enable application default credentials with the Cloud SDK run:: |
| 246 | |
| 247 | gcloud auth application-default login |
| 248 | |
| 249 | If the Cloud SDK has an active project, the project ID is returned. The |
| 250 | active project can be set using:: |
| 251 | |
| 252 | gcloud config set project |
| 253 | |
| 254 | 3. If the application is running in the `App Engine standard environment`_ |
| 255 | then the credentials and project ID from the `App Identity Service`_ |
| 256 | are used. |
| 257 | 4. If the application is running in `Compute Engine`_ or the |
| 258 | `App Engine flexible environment`_ then the credentials and project ID |
| 259 | are obtained from the `Metadata Service`_. |
| 260 | 5. If no credentials are found, |
| 261 | :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. |
| 262 | |
| 263 | .. _Application Default Credentials: https://developers.google.com\ |
| 264 | /identity/protocols/application-default-credentials |
| 265 | .. _Google Cloud SDK: https://cloud.google.com/sdk |
| 266 | .. _App Engine standard environment: https://cloud.google.com/appengine |
| 267 | .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ |
| 268 | /appidentity/ |
| 269 | .. _Compute Engine: https://cloud.google.com/compute |
| 270 | .. _App Engine flexible environment: https://cloud.google.com\ |
| 271 | /appengine/flexible |
| 272 | .. _Metadata Service: https://cloud.google.com/compute/docs\ |
| 273 | /storing-retrieving-metadata |
| 274 | |
| 275 | Example:: |
| 276 | |
| 277 | import google.auth |
| 278 | |
| 279 | credentials, project_id = google.auth.default() |
| 280 | |
| 281 | Args: |
Jon Wayne Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 282 | scopes (Sequence[str]): The list of scopes for the credentials. If |
| 283 | specified, the credentials will automatically be scoped if |
| 284 | necessary. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 285 | request (google.auth.transport.Request): An object used to make |
| 286 | HTTP requests. This is used to detect whether the application |
| 287 | is running on Compute Engine. If not specified, then it will |
| 288 | use the standard library http client to make requests. |
| 289 | |
| 290 | Returns: |
| 291 | Tuple[~google.auth.credentials.Credentials, Optional[str]]: |
| 292 | the current environment's credentials and project ID. Project ID |
| 293 | may be None, which indicates that the Project ID could not be |
| 294 | ascertained from the environment. |
| 295 | |
| 296 | Raises: |
| 297 | ~google.auth.exceptions.DefaultCredentialsError: |
| 298 | If no credentials were found, or if the credentials found were |
| 299 | invalid. |
| 300 | """ |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 301 | from google.auth.credentials import with_scopes_if_required |
| 302 | |
Jon Wayne Parrott | ce37cba | 2016-11-07 16:41:42 -0800 | [diff] [blame] | 303 | explicit_project_id = os.environ.get( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 304 | environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) |
| 305 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 306 | |
| 307 | checkers = ( |
| 308 | _get_explicit_environ_credentials, |
| 309 | _get_gcloud_sdk_credentials, |
| 310 | _get_gae_credentials, |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 311 | lambda: _get_gce_credentials(request), |
| 312 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 313 | |
| 314 | for checker in checkers: |
| 315 | credentials, project_id = checker() |
| 316 | if credentials is not None: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 317 | credentials = with_scopes_if_required(credentials, scopes) |
Jacob Hayes | 15af07b | 2017-12-13 14:09:47 -0600 | [diff] [blame] | 318 | effective_project_id = explicit_project_id or project_id |
| 319 | if not effective_project_id: |
| 320 | _LOGGER.warning( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 321 | "No project ID could be determined. Consider running " |
| 322 | "`gcloud config set project` or setting the %s " |
| 323 | "environment variable", |
| 324 | environment_vars.PROJECT, |
| 325 | ) |
Jacob Hayes | 15af07b | 2017-12-13 14:09:47 -0600 | [diff] [blame] | 326 | return credentials, effective_project_id |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 327 | |
| 328 | raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) |