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" |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 37 | _EXTERNAL_ACCOUNT_TYPE = "external_account" |
| 38 | _VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE, _EXTERNAL_ACCOUNT_TYPE) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 39 | |
| 40 | # Help message when no credentials can be found. |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 41 | _HELP_MESSAGE = """\ |
| 42 | Could not automatically determine credentials. Please set {env} or \ |
| 43 | explicitly create credentials and re-run the application. For more \ |
| 44 | information, please see \ |
Christopher Wilcox | f102825 | 2018-09-21 10:03:04 -0700 | [diff] [blame] | 45 | https://cloud.google.com/docs/authentication/getting-started |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 46 | """.format( |
| 47 | env=environment_vars.CREDENTIALS |
| 48 | ).strip() |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 49 | |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 50 | # Warning when using Cloud SDK user credentials |
| 51 | _CLOUD_SDK_CREDENTIALS_WARNING = """\ |
| 52 | Your application has authenticated using end user credentials from Google \ |
arithmetic1728 | f30b45a | 2020-06-17 23:36:04 -0700 | [diff] [blame] | 53 | Cloud SDK without a quota project. You might receive a "quota exceeded" \ |
| 54 | or "API not enabled" error. We recommend you rerun \ |
| 55 | `gcloud auth application-default login` and make sure a quota project is \ |
| 56 | added. Or you can use service accounts instead. For more information \ |
| 57 | about service accounts, see https://cloud.google.com/docs/authentication/""" |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 58 | |
| 59 | |
| 60 | def _warn_about_problematic_credentials(credentials): |
| 61 | """Determines if the credentials are problematic. |
| 62 | |
| 63 | Credentials from the Cloud SDK that are associated with Cloud SDK's project |
| 64 | are problematic because they may not have APIs enabled and have limited |
| 65 | quota. If this is the case, warn about it. |
| 66 | """ |
| 67 | from google.auth import _cloud_sdk |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 68 | |
Thea Flowers | a8d9348 | 2018-05-31 14:52:06 -0700 | [diff] [blame] | 69 | if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID: |
| 70 | warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING) |
| 71 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 72 | |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 73 | def load_credentials_from_file( |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 74 | filename, scopes=None, default_scopes=None, quota_project_id=None, request=None |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 75 | ): |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame] | 76 | """Loads Google credentials from a file. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 77 | |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 78 | The credentials file must be a service account key, stored authorized |
| 79 | user credentials or external account credentials. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 80 | |
| 81 | Args: |
| 82 | filename (str): The full path to the credentials file. |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame] | 83 | scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If |
| 84 | specified, the credentials will automatically be scoped if |
Bu Sun Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 85 | necessary |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 86 | default_scopes (Optional[Sequence[str]]): Default scopes passed by a |
| 87 | Google client library. Use 'scopes' for user-defined scopes. |
Bu Sun Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 88 | quota_project_id (Optional[str]): The project ID used for |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 89 | quota and billing. |
| 90 | request (Optional[google.auth.transport.Request]): An object used to make |
| 91 | HTTP requests. This is used to determine the associated project ID |
| 92 | for a workload identity pool resource (external account credentials). |
| 93 | If not specified, then it will use a |
| 94 | google.auth.transport.requests.Request client to make requests. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 95 | |
| 96 | Returns: |
| 97 | Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded |
| 98 | credentials and the project ID. Authorized user credentials do not |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 99 | have the project ID information. External account credentials project |
| 100 | IDs may not always be determined. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 101 | |
| 102 | Raises: |
| 103 | google.auth.exceptions.DefaultCredentialsError: if the file is in the |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 104 | wrong format or is missing. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 105 | """ |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 106 | if not os.path.exists(filename): |
| 107 | raise exceptions.DefaultCredentialsError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 108 | "File {} was not found.".format(filename) |
| 109 | ) |
weitaiting | 6e86c93 | 2017-08-12 03:26:59 +0800 | [diff] [blame] | 110 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 111 | with io.open(filename, "r") as file_obj: |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 112 | try: |
| 113 | info = json.load(file_obj) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 114 | except ValueError as caught_exc: |
| 115 | new_exc = exceptions.DefaultCredentialsError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 116 | "File {} is not a valid json file.".format(filename), caught_exc |
| 117 | ) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 118 | six.raise_from(new_exc, caught_exc) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 119 | |
| 120 | # The type key should indicate that the file is either a service account |
| 121 | # credentials file or an authorized user credentials file. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 122 | credential_type = info.get("type") |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 123 | |
| 124 | if credential_type == _AUTHORIZED_USER_TYPE: |
arithmetic1728 | 772dac6 | 2020-03-27 14:34:13 -0700 | [diff] [blame] | 125 | from google.oauth2 import credentials |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 126 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 127 | try: |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame] | 128 | credentials = credentials.Credentials.from_authorized_user_info( |
| 129 | info, scopes=scopes |
Bu Sun Kim | ab2be5d | 2020-07-15 16:49:27 -0700 | [diff] [blame] | 130 | ) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 131 | except ValueError as caught_exc: |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 132 | msg = "Failed to load authorized user credentials from {}".format(filename) |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 133 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 134 | six.raise_from(new_exc, caught_exc) |
Bu Sun Kim | ab2be5d | 2020-07-15 16:49:27 -0700 | [diff] [blame] | 135 | if quota_project_id: |
| 136 | credentials = credentials.with_quota_project(quota_project_id) |
arithmetic1728 | f30b45a | 2020-06-17 23:36:04 -0700 | [diff] [blame] | 137 | if not credentials.quota_project_id: |
| 138 | _warn_about_problematic_credentials(credentials) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 139 | return credentials, None |
| 140 | |
| 141 | elif credential_type == _SERVICE_ACCOUNT_TYPE: |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 142 | from google.oauth2 import service_account |
| 143 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 144 | try: |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame] | 145 | credentials = service_account.Credentials.from_service_account_info( |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 146 | info, scopes=scopes, default_scopes=default_scopes |
Bu Sun Kim | ab2be5d | 2020-07-15 16:49:27 -0700 | [diff] [blame] | 147 | ) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 148 | except ValueError as caught_exc: |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 149 | msg = "Failed to load service account credentials from {}".format(filename) |
Danny Hermes | 0a93e87 | 2017-11-09 12:18:58 -0800 | [diff] [blame] | 150 | new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) |
Danny Hermes | 895e369 | 2017-11-09 11:35:57 -0800 | [diff] [blame] | 151 | six.raise_from(new_exc, caught_exc) |
Bu Sun Kim | ab2be5d | 2020-07-15 16:49:27 -0700 | [diff] [blame] | 152 | if quota_project_id: |
| 153 | credentials = credentials.with_quota_project(quota_project_id) |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 154 | return credentials, info.get("project_id") |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 155 | |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 156 | elif credential_type == _EXTERNAL_ACCOUNT_TYPE: |
| 157 | credentials, project_id = _get_external_account_credentials( |
| 158 | info, |
| 159 | filename, |
| 160 | scopes=scopes, |
| 161 | default_scopes=default_scopes, |
| 162 | request=request, |
| 163 | ) |
| 164 | if quota_project_id: |
| 165 | credentials = credentials.with_quota_project(quota_project_id) |
| 166 | return credentials, project_id |
| 167 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 168 | else: |
| 169 | raise exceptions.DefaultCredentialsError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 170 | "The file {file} does not have a valid type. " |
| 171 | "Type is {type}, expected one of {valid_types}.".format( |
| 172 | file=filename, type=credential_type, valid_types=_VALID_TYPES |
| 173 | ) |
| 174 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 175 | |
| 176 | |
| 177 | def _get_gcloud_sdk_credentials(): |
| 178 | """Gets the credentials and project ID from the Cloud SDK.""" |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 179 | from google.auth import _cloud_sdk |
| 180 | |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 181 | _LOGGER.debug("Checking Cloud SDK credentials as part of auth process...") |
| 182 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 183 | # Check if application default credentials exist. |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 184 | credentials_filename = _cloud_sdk.get_application_default_credentials_path() |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 185 | |
| 186 | if not os.path.isfile(credentials_filename): |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 187 | _LOGGER.debug("Cloud SDK credentials not found on disk; not using them") |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 188 | return None, None |
| 189 | |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame] | 190 | credentials, project_id = load_credentials_from_file(credentials_filename) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 191 | |
| 192 | if not project_id: |
| 193 | project_id = _cloud_sdk.get_project_id() |
| 194 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 195 | return credentials, project_id |
| 196 | |
| 197 | |
Bu Sun Kim | 9dc2d86 | 2021-02-11 12:53:26 -0700 | [diff] [blame] | 198 | def _get_explicit_environ_credentials(): |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 199 | """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment |
Bu Sun Kim | 9dc2d86 | 2021-02-11 12:53:26 -0700 | [diff] [blame] | 200 | variable.""" |
arithmetic1728 | 333cb76 | 2021-02-25 15:42:32 -0800 | [diff] [blame] | 201 | from google.auth import _cloud_sdk |
| 202 | |
| 203 | cloud_sdk_adc_path = _cloud_sdk.get_application_default_credentials_path() |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 204 | explicit_file = os.environ.get(environment_vars.CREDENTIALS) |
| 205 | |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 206 | _LOGGER.debug( |
| 207 | "Checking %s for explicit credentials as part of auth process...", explicit_file |
| 208 | ) |
| 209 | |
arithmetic1728 | 333cb76 | 2021-02-25 15:42:32 -0800 | [diff] [blame] | 210 | if explicit_file is not None and explicit_file == cloud_sdk_adc_path: |
| 211 | # Cloud sdk flow calls gcloud to fetch project id, so if the explicit |
| 212 | # file path is cloud sdk credentials path, then we should fall back |
| 213 | # to cloud sdk flow, otherwise project id cannot be obtained. |
| 214 | _LOGGER.debug( |
| 215 | "Explicit credentials path %s is the same as Cloud SDK credentials path, fall back to Cloud SDK credentials flow...", |
| 216 | explicit_file, |
| 217 | ) |
| 218 | return _get_gcloud_sdk_credentials() |
| 219 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 220 | if explicit_file is not None: |
Bu Sun Kim | 15d5fa9 | 2020-06-18 14:05:40 -0700 | [diff] [blame] | 221 | credentials, project_id = load_credentials_from_file( |
Bu Sun Kim | 9dc2d86 | 2021-02-11 12:53:26 -0700 | [diff] [blame] | 222 | os.environ[environment_vars.CREDENTIALS] |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 223 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 224 | |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 225 | return credentials, project_id |
| 226 | |
| 227 | else: |
| 228 | return None, None |
| 229 | |
| 230 | |
| 231 | def _get_gae_credentials(): |
| 232 | """Gets Google App Engine App Identity credentials and project ID.""" |
Zev Goldstein | 7f7d92d | 2021-07-23 15:52:46 -0400 | [diff] [blame] | 233 | # If not GAE gen1, prefer the metadata service even if the GAE APIs are |
| 234 | # available as per https://google.aip.dev/auth/4115. |
| 235 | if os.environ.get(environment_vars.LEGACY_APPENGINE_RUNTIME) != "python27": |
| 236 | return None, None |
| 237 | |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 238 | # While this library is normally bundled with app_engine, there are |
| 239 | # some cases where it's not available, so we tolerate ImportError. |
| 240 | try: |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 241 | _LOGGER.debug("Checking for App Engine runtime as part of auth process...") |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 242 | import google.auth.app_engine as app_engine |
| 243 | except ImportError: |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 244 | _LOGGER.warning("Import of App Engine auth library failed.") |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 245 | return None, None |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 246 | |
Jon Wayne Parrott | 2148fde | 2016-10-24 13:44:25 -0700 | [diff] [blame] | 247 | try: |
| 248 | credentials = app_engine.Credentials() |
| 249 | project_id = app_engine.get_project_id() |
| 250 | return credentials, project_id |
| 251 | except EnvironmentError: |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 252 | _LOGGER.debug( |
| 253 | "No App Engine library was found so cannot authentication via App Engine Identity Credentials." |
| 254 | ) |
Jon Wayne Parrott | 2148fde | 2016-10-24 13:44:25 -0700 | [diff] [blame] | 255 | return None, None |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 256 | |
| 257 | |
| 258 | def _get_gce_credentials(request=None): |
| 259 | """Gets credentials and project ID from the GCE Metadata Service.""" |
| 260 | # Ping requires a transport, but we want application default credentials |
| 261 | # to require no arguments. So, we'll use the _http_client transport which |
| 262 | # uses http.client. This is only acceptable because the metadata server |
| 263 | # doesn't do SSL and never requires proxies. |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 264 | |
| 265 | # While this library is normally bundled with compute_engine, there are |
| 266 | # some cases where it's not available, so we tolerate ImportError. |
| 267 | try: |
| 268 | from google.auth import compute_engine |
| 269 | from google.auth.compute_engine import _metadata |
| 270 | except ImportError: |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 271 | _LOGGER.warning("Import of Compute Engine auth library failed.") |
James Wilson | 6e0781b | 2018-12-20 20:38:52 -0500 | [diff] [blame] | 272 | return None, None |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 273 | |
| 274 | if request is None: |
| 275 | request = google.auth.transport._http_client.Request() |
| 276 | |
| 277 | if _metadata.ping(request=request): |
| 278 | # Get the project ID. |
| 279 | try: |
Jon Wayne Parrott | 5b03ba1 | 2016-10-24 13:51:26 -0700 | [diff] [blame] | 280 | project_id = _metadata.get_project_id(request=request) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 281 | except exceptions.TransportError: |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 282 | project_id = None |
| 283 | |
| 284 | return compute_engine.Credentials(), project_id |
| 285 | else: |
Vaughan Hilts | ecd88d4 | 2020-07-21 16:25:51 -0400 | [diff] [blame] | 286 | _LOGGER.warning( |
| 287 | "Authentication failed using Compute Engine authentication due to unavailable metadata server." |
| 288 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 289 | return None, None |
| 290 | |
| 291 | |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 292 | def _get_external_account_credentials( |
| 293 | info, filename, scopes=None, default_scopes=None, request=None |
| 294 | ): |
| 295 | """Loads external account Credentials from the parsed external account info. |
| 296 | |
| 297 | The credentials information must correspond to a supported external account |
| 298 | credentials. |
| 299 | |
| 300 | Args: |
| 301 | info (Mapping[str, str]): The external account info in Google format. |
| 302 | filename (str): The full path to the credentials file. |
| 303 | scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If |
| 304 | specified, the credentials will automatically be scoped if |
| 305 | necessary. |
| 306 | default_scopes (Optional[Sequence[str]]): Default scopes passed by a |
| 307 | Google client library. Use 'scopes' for user-defined scopes. |
| 308 | request (Optional[google.auth.transport.Request]): An object used to make |
| 309 | HTTP requests. This is used to determine the associated project ID |
| 310 | for a workload identity pool resource (external account credentials). |
| 311 | If not specified, then it will use a |
| 312 | google.auth.transport.requests.Request client to make requests. |
| 313 | |
| 314 | Returns: |
| 315 | Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded |
| 316 | credentials and the project ID. External account credentials project |
| 317 | IDs may not always be determined. |
| 318 | |
| 319 | Raises: |
| 320 | google.auth.exceptions.DefaultCredentialsError: if the info dictionary |
| 321 | is in the wrong format or is missing required information. |
| 322 | """ |
| 323 | # There are currently 2 types of external_account credentials. |
| 324 | try: |
| 325 | # Check if configuration corresponds to an AWS credentials. |
| 326 | from google.auth import aws |
| 327 | |
| 328 | credentials = aws.Credentials.from_info( |
| 329 | info, scopes=scopes, default_scopes=default_scopes |
| 330 | ) |
| 331 | except ValueError: |
| 332 | try: |
| 333 | # Check if configuration corresponds to an Identity Pool credentials. |
| 334 | from google.auth import identity_pool |
| 335 | |
| 336 | credentials = identity_pool.Credentials.from_info( |
| 337 | info, scopes=scopes, default_scopes=default_scopes |
| 338 | ) |
| 339 | except ValueError: |
| 340 | # If the configuration is invalid or does not correspond to any |
| 341 | # supported external_account credentials, raise an error. |
| 342 | raise exceptions.DefaultCredentialsError( |
| 343 | "Failed to load external account credentials from {}".format(filename) |
| 344 | ) |
| 345 | if request is None: |
| 346 | request = google.auth.transport.requests.Request() |
| 347 | |
| 348 | return credentials, credentials.get_project_id(request=request) |
| 349 | |
| 350 | |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 351 | def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 352 | """Gets the default credentials for the current environment. |
| 353 | |
| 354 | `Application Default Credentials`_ provides an easy way to obtain |
| 355 | credentials to call Google APIs for server-to-server or local applications. |
| 356 | This function acquires credentials from the environment in the following |
| 357 | order: |
| 358 | |
| 359 | 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set |
| 360 | to the path of a valid service account JSON private key file, then it is |
| 361 | loaded and returned. The project ID returned is the project ID defined |
| 362 | in the service account file if available (some older files do not |
| 363 | contain project ID information). |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 364 | |
| 365 | If the environment variable is set to the path of a valid external |
| 366 | account JSON configuration file (workload identity federation), then the |
| 367 | configuration file is used to determine and retrieve the external |
| 368 | credentials from the current environment (AWS, Azure, etc). |
| 369 | These will then be exchanged for Google access tokens via the Google STS |
| 370 | endpoint. |
| 371 | The project ID returned in this case is the one corresponding to the |
| 372 | underlying workload identity pool resource if determinable. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 373 | 2. If the `Google Cloud SDK`_ is installed and has application default |
| 374 | credentials set they are loaded and returned. |
| 375 | |
| 376 | To enable application default credentials with the Cloud SDK run:: |
| 377 | |
| 378 | gcloud auth application-default login |
| 379 | |
| 380 | If the Cloud SDK has an active project, the project ID is returned. The |
| 381 | active project can be set using:: |
| 382 | |
| 383 | gcloud config set project |
| 384 | |
| 385 | 3. If the application is running in the `App Engine standard environment`_ |
David Buxton | 0323cf3 | 2020-10-29 21:26:11 +0000 | [diff] [blame] | 386 | (first generation) then the credentials and project ID from the |
| 387 | `App Identity Service`_ are used. |
| 388 | 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or |
| 389 | the `App Engine flexible environment`_ or the `App Engine standard |
| 390 | environment`_ (second generation) then the credentials and project ID |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 391 | are obtained from the `Metadata Service`_. |
| 392 | 5. If no credentials are found, |
| 393 | :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. |
| 394 | |
| 395 | .. _Application Default Credentials: https://developers.google.com\ |
| 396 | /identity/protocols/application-default-credentials |
| 397 | .. _Google Cloud SDK: https://cloud.google.com/sdk |
| 398 | .. _App Engine standard environment: https://cloud.google.com/appengine |
| 399 | .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ |
| 400 | /appidentity/ |
| 401 | .. _Compute Engine: https://cloud.google.com/compute |
| 402 | .. _App Engine flexible environment: https://cloud.google.com\ |
| 403 | /appengine/flexible |
| 404 | .. _Metadata Service: https://cloud.google.com/compute/docs\ |
| 405 | /storing-retrieving-metadata |
David Buxton | 0323cf3 | 2020-10-29 21:26:11 +0000 | [diff] [blame] | 406 | .. _Cloud Run: https://cloud.google.com/run |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 407 | |
| 408 | Example:: |
| 409 | |
| 410 | import google.auth |
| 411 | |
| 412 | credentials, project_id = google.auth.default() |
| 413 | |
| 414 | Args: |
Jon Wayne Parrott | 8a7e506 | 2016-11-07 16:45:17 -0800 | [diff] [blame] | 415 | scopes (Sequence[str]): The list of scopes for the credentials. If |
| 416 | specified, the credentials will automatically be scoped if |
| 417 | necessary. |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 418 | request (Optional[google.auth.transport.Request]): An object used to make |
| 419 | HTTP requests. This is used to either detect whether the application |
| 420 | is running on Compute Engine or to determine the associated project |
| 421 | ID for a workload identity pool resource (external account |
| 422 | credentials). If not specified, then it will either use the standard |
| 423 | library http client to make requests for Compute Engine credentials |
| 424 | or a google.auth.transport.requests.Request client for external |
| 425 | account credentials. |
| 426 | quota_project_id (Optional[str]): The project ID used for |
Bu Sun Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 427 | quota and billing. |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 428 | default_scopes (Optional[Sequence[str]]): Default scopes passed by a |
| 429 | Google client library. Use 'scopes' for user-defined scopes. |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 430 | Returns: |
| 431 | Tuple[~google.auth.credentials.Credentials, Optional[str]]: |
| 432 | the current environment's credentials and project ID. Project ID |
| 433 | may be None, which indicates that the Project ID could not be |
| 434 | ascertained from the environment. |
| 435 | |
| 436 | Raises: |
| 437 | ~google.auth.exceptions.DefaultCredentialsError: |
| 438 | If no credentials were found, or if the credentials found were |
| 439 | invalid. |
| 440 | """ |
Jon Wayne Parrott | 6dca98c | 2016-12-01 15:34:59 -0800 | [diff] [blame] | 441 | from google.auth.credentials import with_scopes_if_required |
| 442 | |
Jon Wayne Parrott | ce37cba | 2016-11-07 16:41:42 -0800 | [diff] [blame] | 443 | explicit_project_id = os.environ.get( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 444 | environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) |
| 445 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 446 | |
| 447 | checkers = ( |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 448 | # Avoid passing scopes here to prevent passing scopes to user credentials. |
| 449 | # with_scopes_if_required() below will ensure scopes/default scopes are |
| 450 | # safely set on the returned credentials since requires_scopes will |
| 451 | # guard against setting scopes on user credentials. |
Bu Sun Kim | 9dc2d86 | 2021-02-11 12:53:26 -0700 | [diff] [blame] | 452 | _get_explicit_environ_credentials, |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 453 | _get_gcloud_sdk_credentials, |
| 454 | _get_gae_credentials, |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 455 | lambda: _get_gce_credentials(request), |
| 456 | ) |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 457 | |
| 458 | for checker in checkers: |
| 459 | credentials, project_id = checker() |
| 460 | if credentials is not None: |
Bu Sun Kim | bf5ce0c | 2021-02-01 15:17:49 -0700 | [diff] [blame] | 461 | credentials = with_scopes_if_required( |
| 462 | credentials, scopes, default_scopes=default_scopes |
| 463 | ) |
bojeil-google | d4d7f38 | 2021-02-16 12:33:20 -0800 | [diff] [blame] | 464 | |
| 465 | # For external account credentials, scopes are required to determine |
| 466 | # the project ID. Try to get the project ID again if not yet |
| 467 | # determined. |
| 468 | if not project_id and callable( |
| 469 | getattr(credentials, "get_project_id", None) |
| 470 | ): |
| 471 | if request is None: |
| 472 | request = google.auth.transport.requests.Request() |
| 473 | project_id = credentials.get_project_id(request=request) |
| 474 | |
Bu Sun Kim | ab2be5d | 2020-07-15 16:49:27 -0700 | [diff] [blame] | 475 | if quota_project_id: |
| 476 | credentials = credentials.with_quota_project(quota_project_id) |
| 477 | |
Jacob Hayes | 15af07b | 2017-12-13 14:09:47 -0600 | [diff] [blame] | 478 | effective_project_id = explicit_project_id or project_id |
| 479 | if not effective_project_id: |
| 480 | _LOGGER.warning( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 481 | "No project ID could be determined. Consider running " |
| 482 | "`gcloud config set project` or setting the %s " |
| 483 | "environment variable", |
| 484 | environment_vars.PROJECT, |
| 485 | ) |
Jacob Hayes | 15af07b | 2017-12-13 14:09:47 -0600 | [diff] [blame] | 486 | return credentials, effective_project_id |
Jon Wayne Parrott | aadb3de | 2016-10-19 09:34:05 -0700 | [diff] [blame] | 487 | |
| 488 | raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) |