We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
_default always sets `credentials.quota_project_id` to None
#546 introduced a bug where the quota project id always gets set to `None`. If no `quota_project_id` is passed to `load_credentials_from_file(...)` or `default(...)`, the existing project should not be overridden

--- END ISSUE ---

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

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/google/auth/_default.py b/google/auth/_default.py
--- a/google/auth/_default.py
+++ b/google/auth/_default.py
@@ -116,11 +116,13 @@
         try:
             credentials = credentials.Credentials.from_authorized_user_info(
                 info, scopes=scopes
-            ).with_quota_project(quota_project_id)
+            )
         except ValueError as caught_exc:
             msg = "Failed to load authorized user credentials from {}".format(filename)
             new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
             six.raise_from(new_exc, caught_exc)
+        if quota_project_id:
+            credentials = credentials.with_quota_project(quota_project_id)
         if not credentials.quota_project_id:
             _warn_about_problematic_credentials(credentials)
         return credentials, None
@@ -131,11 +133,13 @@
         try:
             credentials = service_account.Credentials.from_service_account_info(
                 info, scopes=scopes
-            ).with_quota_project(quota_project_id)
+            )
         except ValueError as caught_exc:
             msg = "Failed to load service account credentials from {}".format(filename)
             new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
             six.raise_from(new_exc, caught_exc)
+        if quota_project_id:
+            credentials = credentials.with_quota_project(quota_project_id)
         return credentials, info.get("project_id")
 
     else:
@@ -317,9 +321,10 @@
     for checker in checkers:
         credentials, project_id = checker()
         if credentials is not None:
-            credentials = with_scopes_if_required(
-                credentials, scopes
-            ).with_quota_project(quota_project_id)
+            credentials = with_scopes_if_required(credentials, scopes)
+            if quota_project_id:
+                credentials = credentials.with_quota_project(quota_project_id)
+
             effective_project_id = explicit_project_id or project_id
             if not effective_project_id:
                 _LOGGER.warning(

{"golden_diff": "diff --git a/google/auth/_default.py b/google/auth/_default.py\n--- a/google/auth/_default.py\n+++ b/google/auth/_default.py\n@@ -116,11 +116,13 @@\n         try:\n             credentials = credentials.Credentials.from_authorized_user_info(\n                 info, scopes=scopes\n-            ).with_quota_project(quota_project_id)\n+            )\n         except ValueError as caught_exc:\n             msg = \"Failed to load authorized user credentials from {}\".format(filename)\n             new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)\n             six.raise_from(new_exc, caught_exc)\n+        if quota_project_id:\n+            credentials = credentials.with_quota_project(quota_project_id)\n         if not credentials.quota_project_id:\n             _warn_about_problematic_credentials(credentials)\n         return credentials, None\n@@ -131,11 +133,13 @@\n         try:\n             credentials = service_account.Credentials.from_service_account_info(\n                 info, scopes=scopes\n-            ).with_quota_project(quota_project_id)\n+            )\n         except ValueError as caught_exc:\n             msg = \"Failed to load service account credentials from {}\".format(filename)\n             new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)\n             six.raise_from(new_exc, caught_exc)\n+        if quota_project_id:\n+            credentials = credentials.with_quota_project(quota_project_id)\n         return credentials, info.get(\"project_id\")\n \n     else:\n@@ -317,9 +321,10 @@\n     for checker in checkers:\n         credentials, project_id = checker()\n         if credentials is not None:\n-            credentials = with_scopes_if_required(\n-                credentials, scopes\n-            ).with_quota_project(quota_project_id)\n+            credentials = with_scopes_if_required(credentials, scopes)\n+            if quota_project_id:\n+                credentials = credentials.with_quota_project(quota_project_id)\n+\n             effective_project_id = explicit_project_id or project_id\n             if not effective_project_id:\n                 _LOGGER.warning(\n", "issue": "_default always sets `credentials.quota_project_id` to None\n#546 introduced a bug where the quota project id always gets set to `None`. If no `quota_project_id` is passed to `load_credentials_from_file(...)` or `default(...)`, the existing project should not be overridden\n", "before_files": [{"content": "# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Application default credentials.\n\nImplements application default credentials and project ID detection.\n\"\"\"\n\nimport io\nimport json\nimport logging\nimport os\nimport warnings\n\nimport six\n\nfrom google.auth import environment_vars\nfrom google.auth import exceptions\nimport google.auth.transport._http_client\n\n_LOGGER = logging.getLogger(__name__)\n\n# Valid types accepted for file-based credentials.\n_AUTHORIZED_USER_TYPE = \"authorized_user\"\n_SERVICE_ACCOUNT_TYPE = \"service_account\"\n_VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE)\n\n# Help message when no credentials can be found.\n_HELP_MESSAGE = \"\"\"\\\nCould not automatically determine credentials. Please set {env} or \\\nexplicitly create credentials and re-run the application. For more \\\ninformation, please see \\\nhttps://cloud.google.com/docs/authentication/getting-started\n\"\"\".format(\n    env=environment_vars.CREDENTIALS\n).strip()\n\n# Warning when using Cloud SDK user credentials\n_CLOUD_SDK_CREDENTIALS_WARNING = \"\"\"\\\nYour application has authenticated using end user credentials from Google \\\nCloud SDK without a quota project. You might receive a \"quota exceeded\" \\\nor \"API not enabled\" error. We recommend you rerun \\\n`gcloud auth application-default login` and make sure a quota project is \\\nadded. Or you can use service accounts instead. For more information \\\nabout service accounts, see https://cloud.google.com/docs/authentication/\"\"\"\n\n\ndef _warn_about_problematic_credentials(credentials):\n    \"\"\"Determines if the credentials are problematic.\n\n    Credentials from the Cloud SDK that are associated with Cloud SDK's project\n    are problematic because they may not have APIs enabled and have limited\n    quota. If this is the case, warn about it.\n    \"\"\"\n    from google.auth import _cloud_sdk\n\n    if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:\n        warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)\n\n\ndef load_credentials_from_file(filename, scopes=None, quota_project_id=None):\n    \"\"\"Loads Google credentials from a file.\n\n    The credentials file must be a service account key or stored authorized\n    user credentials.\n\n    Args:\n        filename (str): The full path to the credentials file.\n        scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If\n            specified, the credentials will automatically be scoped if\n            necessary\n        quota_project_id (Optional[str]):  The project ID used for\n                quota and billing.\n\n    Returns:\n        Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded\n            credentials and the project ID. Authorized user credentials do not\n            have the project ID information.\n\n    Raises:\n        google.auth.exceptions.DefaultCredentialsError: if the file is in the\n            wrong format or is missing.\n    \"\"\"\n    if not os.path.exists(filename):\n        raise exceptions.DefaultCredentialsError(\n            \"File {} was not found.\".format(filename)\n        )\n\n    with io.open(filename, \"r\") as file_obj:\n        try:\n            info = json.load(file_obj)\n        except ValueError as caught_exc:\n            new_exc = exceptions.DefaultCredentialsError(\n                \"File {} is not a valid json file.\".format(filename), caught_exc\n            )\n            six.raise_from(new_exc, caught_exc)\n\n    # The type key should indicate that the file is either a service account\n    # credentials file or an authorized user credentials file.\n    credential_type = info.get(\"type\")\n\n    if credential_type == _AUTHORIZED_USER_TYPE:\n        from google.oauth2 import credentials\n\n        try:\n            credentials = credentials.Credentials.from_authorized_user_info(\n                info, scopes=scopes\n            ).with_quota_project(quota_project_id)\n        except ValueError as caught_exc:\n            msg = \"Failed to load authorized user credentials from {}\".format(filename)\n            new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)\n            six.raise_from(new_exc, caught_exc)\n        if not credentials.quota_project_id:\n            _warn_about_problematic_credentials(credentials)\n        return credentials, None\n\n    elif credential_type == _SERVICE_ACCOUNT_TYPE:\n        from google.oauth2 import service_account\n\n        try:\n            credentials = service_account.Credentials.from_service_account_info(\n                info, scopes=scopes\n            ).with_quota_project(quota_project_id)\n        except ValueError as caught_exc:\n            msg = \"Failed to load service account credentials from {}\".format(filename)\n            new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)\n            six.raise_from(new_exc, caught_exc)\n        return credentials, info.get(\"project_id\")\n\n    else:\n        raise exceptions.DefaultCredentialsError(\n            \"The file {file} does not have a valid type. \"\n            \"Type is {type}, expected one of {valid_types}.\".format(\n                file=filename, type=credential_type, valid_types=_VALID_TYPES\n            )\n        )\n\n\ndef _get_gcloud_sdk_credentials():\n    \"\"\"Gets the credentials and project ID from the Cloud SDK.\"\"\"\n    from google.auth import _cloud_sdk\n\n    # Check if application default credentials exist.\n    credentials_filename = _cloud_sdk.get_application_default_credentials_path()\n\n    if not os.path.isfile(credentials_filename):\n        return None, None\n\n    credentials, project_id = load_credentials_from_file(credentials_filename)\n\n    if not project_id:\n        project_id = _cloud_sdk.get_project_id()\n\n    return credentials, project_id\n\n\ndef _get_explicit_environ_credentials():\n    \"\"\"Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment\n    variable.\"\"\"\n    explicit_file = os.environ.get(environment_vars.CREDENTIALS)\n\n    if explicit_file is not None:\n        credentials, project_id = load_credentials_from_file(\n            os.environ[environment_vars.CREDENTIALS]\n        )\n\n        return credentials, project_id\n\n    else:\n        return None, None\n\n\ndef _get_gae_credentials():\n    \"\"\"Gets Google App Engine App Identity credentials and project ID.\"\"\"\n    # While this library is normally bundled with app_engine, there are\n    # some cases where it's not available, so we tolerate ImportError.\n    try:\n        import google.auth.app_engine as app_engine\n    except ImportError:\n        return None, None\n\n    try:\n        credentials = app_engine.Credentials()\n        project_id = app_engine.get_project_id()\n        return credentials, project_id\n    except EnvironmentError:\n        return None, None\n\n\ndef _get_gce_credentials(request=None):\n    \"\"\"Gets credentials and project ID from the GCE Metadata Service.\"\"\"\n    # Ping requires a transport, but we want application default credentials\n    # to require no arguments. So, we'll use the _http_client transport which\n    # uses http.client. This is only acceptable because the metadata server\n    # doesn't do SSL and never requires proxies.\n\n    # While this library is normally bundled with compute_engine, there are\n    # some cases where it's not available, so we tolerate ImportError.\n    try:\n        from google.auth import compute_engine\n        from google.auth.compute_engine import _metadata\n    except ImportError:\n        return None, None\n\n    if request is None:\n        request = google.auth.transport._http_client.Request()\n\n    if _metadata.ping(request=request):\n        # Get the project ID.\n        try:\n            project_id = _metadata.get_project_id(request=request)\n        except exceptions.TransportError:\n            project_id = None\n\n        return compute_engine.Credentials(), project_id\n    else:\n        return None, None\n\n\ndef default(scopes=None, request=None, quota_project_id=None):\n    \"\"\"Gets the default credentials for the current environment.\n\n    `Application Default Credentials`_ provides an easy way to obtain\n    credentials to call Google APIs for server-to-server or local applications.\n    This function acquires credentials from the environment in the following\n    order:\n\n    1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set\n       to the path of a valid service account JSON private key file, then it is\n       loaded and returned. The project ID returned is the project ID defined\n       in the service account file if available (some older files do not\n       contain project ID information).\n    2. If the `Google Cloud SDK`_ is installed and has application default\n       credentials set they are loaded and returned.\n\n       To enable application default credentials with the Cloud SDK run::\n\n            gcloud auth application-default login\n\n       If the Cloud SDK has an active project, the project ID is returned. The\n       active project can be set using::\n\n            gcloud config set project\n\n    3. If the application is running in the `App Engine standard environment`_\n       then the credentials and project ID from the `App Identity Service`_\n       are used.\n    4. If the application is running in `Compute Engine`_ or the\n       `App Engine flexible environment`_ then the credentials and project ID\n       are obtained from the `Metadata Service`_.\n    5. If no credentials are found,\n       :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.\n\n    .. _Application Default Credentials: https://developers.google.com\\\n            /identity/protocols/application-default-credentials\n    .. _Google Cloud SDK: https://cloud.google.com/sdk\n    .. _App Engine standard environment: https://cloud.google.com/appengine\n    .. _App Identity Service: https://cloud.google.com/appengine/docs/python\\\n            /appidentity/\n    .. _Compute Engine: https://cloud.google.com/compute\n    .. _App Engine flexible environment: https://cloud.google.com\\\n            /appengine/flexible\n    .. _Metadata Service: https://cloud.google.com/compute/docs\\\n            /storing-retrieving-metadata\n\n    Example::\n\n        import google.auth\n\n        credentials, project_id = google.auth.default()\n\n    Args:\n        scopes (Sequence[str]): The list of scopes for the credentials. If\n            specified, the credentials will automatically be scoped if\n            necessary.\n        request (google.auth.transport.Request): An object used to make\n            HTTP requests. This is used to detect whether the application\n            is running on Compute Engine. If not specified, then it will\n            use the standard library http client to make requests.\n        quota_project_id (Optional[str]):  The project ID used for\n            quota and billing.\n    Returns:\n        Tuple[~google.auth.credentials.Credentials, Optional[str]]:\n            the current environment's credentials and project ID. Project ID\n            may be None, which indicates that the Project ID could not be\n            ascertained from the environment.\n\n    Raises:\n        ~google.auth.exceptions.DefaultCredentialsError:\n            If no credentials were found, or if the credentials found were\n            invalid.\n    \"\"\"\n    from google.auth.credentials import with_scopes_if_required\n\n    explicit_project_id = os.environ.get(\n        environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)\n    )\n\n    checkers = (\n        _get_explicit_environ_credentials,\n        _get_gcloud_sdk_credentials,\n        _get_gae_credentials,\n        lambda: _get_gce_credentials(request),\n    )\n\n    for checker in checkers:\n        credentials, project_id = checker()\n        if credentials is not None:\n            credentials = with_scopes_if_required(\n                credentials, scopes\n            ).with_quota_project(quota_project_id)\n            effective_project_id = explicit_project_id or project_id\n            if not effective_project_id:\n                _LOGGER.warning(\n                    \"No project ID could be determined. Consider running \"\n                    \"`gcloud config set project` or setting the %s \"\n                    \"environment variable\",\n                    environment_vars.PROJECT,\n                )\n            return credentials, effective_project_id\n\n    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)\n", "path": "google/auth/_default.py"}], "after_files": [{"content": "# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Application default credentials.\n\nImplements application default credentials and project ID detection.\n\"\"\"\n\nimport io\nimport json\nimport logging\nimport os\nimport warnings\n\nimport six\n\nfrom google.auth import environment_vars\nfrom google.auth import exceptions\nimport google.auth.transport._http_client\n\n_LOGGER = logging.getLogger(__name__)\n\n# Valid types accepted for file-based credentials.\n_AUTHORIZED_USER_TYPE = \"authorized_user\"\n_SERVICE_ACCOUNT_TYPE = \"service_account\"\n_VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE)\n\n# Help message when no credentials can be found.\n_HELP_MESSAGE = \"\"\"\\\nCould not automatically determine credentials. Please set {env} or \\\nexplicitly create credentials and re-run the application. For more \\\ninformation, please see \\\nhttps://cloud.google.com/docs/authentication/getting-started\n\"\"\".format(\n    env=environment_vars.CREDENTIALS\n).strip()\n\n# Warning when using Cloud SDK user credentials\n_CLOUD_SDK_CREDENTIALS_WARNING = \"\"\"\\\nYour application has authenticated using end user credentials from Google \\\nCloud SDK without a quota project. You might receive a \"quota exceeded\" \\\nor \"API not enabled\" error. We recommend you rerun \\\n`gcloud auth application-default login` and make sure a quota project is \\\nadded. Or you can use service accounts instead. For more information \\\nabout service accounts, see https://cloud.google.com/docs/authentication/\"\"\"\n\n\ndef _warn_about_problematic_credentials(credentials):\n    \"\"\"Determines if the credentials are problematic.\n\n    Credentials from the Cloud SDK that are associated with Cloud SDK's project\n    are problematic because they may not have APIs enabled and have limited\n    quota. If this is the case, warn about it.\n    \"\"\"\n    from google.auth import _cloud_sdk\n\n    if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:\n        warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)\n\n\ndef load_credentials_from_file(filename, scopes=None, quota_project_id=None):\n    \"\"\"Loads Google credentials from a file.\n\n    The credentials file must be a service account key or stored authorized\n    user credentials.\n\n    Args:\n        filename (str): The full path to the credentials file.\n        scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If\n            specified, the credentials will automatically be scoped if\n            necessary\n        quota_project_id (Optional[str]):  The project ID used for\n                quota and billing.\n\n    Returns:\n        Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded\n            credentials and the project ID. Authorized user credentials do not\n            have the project ID information.\n\n    Raises:\n        google.auth.exceptions.DefaultCredentialsError: if the file is in the\n            wrong format or is missing.\n    \"\"\"\n    if not os.path.exists(filename):\n        raise exceptions.DefaultCredentialsError(\n            \"File {} was not found.\".format(filename)\n        )\n\n    with io.open(filename, \"r\") as file_obj:\n        try:\n            info = json.load(file_obj)\n        except ValueError as caught_exc:\n            new_exc = exceptions.DefaultCredentialsError(\n                \"File {} is not a valid json file.\".format(filename), caught_exc\n            )\n            six.raise_from(new_exc, caught_exc)\n\n    # The type key should indicate that the file is either a service account\n    # credentials file or an authorized user credentials file.\n    credential_type = info.get(\"type\")\n\n    if credential_type == _AUTHORIZED_USER_TYPE:\n        from google.oauth2 import credentials\n\n        try:\n            credentials = credentials.Credentials.from_authorized_user_info(\n                info, scopes=scopes\n            )\n        except ValueError as caught_exc:\n            msg = \"Failed to load authorized user credentials from {}\".format(filename)\n            new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)\n            six.raise_from(new_exc, caught_exc)\n        if quota_project_id:\n            credentials = credentials.with_quota_project(quota_project_id)\n        if not credentials.quota_project_id:\n            _warn_about_problematic_credentials(credentials)\n        return credentials, None\n\n    elif credential_type == _SERVICE_ACCOUNT_TYPE:\n        from google.oauth2 import service_account\n\n        try:\n            credentials = service_account.Credentials.from_service_account_info(\n                info, scopes=scopes\n            )\n        except ValueError as caught_exc:\n            msg = \"Failed to load service account credentials from {}\".format(filename)\n            new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)\n            six.raise_from(new_exc, caught_exc)\n        if quota_project_id:\n            credentials = credentials.with_quota_project(quota_project_id)\n        return credentials, info.get(\"project_id\")\n\n    else:\n        raise exceptions.DefaultCredentialsError(\n            \"The file {file} does not have a valid type. \"\n            \"Type is {type}, expected one of {valid_types}.\".format(\n                file=filename, type=credential_type, valid_types=_VALID_TYPES\n            )\n        )\n\n\ndef _get_gcloud_sdk_credentials():\n    \"\"\"Gets the credentials and project ID from the Cloud SDK.\"\"\"\n    from google.auth import _cloud_sdk\n\n    # Check if application default credentials exist.\n    credentials_filename = _cloud_sdk.get_application_default_credentials_path()\n\n    if not os.path.isfile(credentials_filename):\n        return None, None\n\n    credentials, project_id = load_credentials_from_file(credentials_filename)\n\n    if not project_id:\n        project_id = _cloud_sdk.get_project_id()\n\n    return credentials, project_id\n\n\ndef _get_explicit_environ_credentials():\n    \"\"\"Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment\n    variable.\"\"\"\n    explicit_file = os.environ.get(environment_vars.CREDENTIALS)\n\n    if explicit_file is not None:\n        credentials, project_id = load_credentials_from_file(\n            os.environ[environment_vars.CREDENTIALS]\n        )\n\n        return credentials, project_id\n\n    else:\n        return None, None\n\n\ndef _get_gae_credentials():\n    \"\"\"Gets Google App Engine App Identity credentials and project ID.\"\"\"\n    # While this library is normally bundled with app_engine, there are\n    # some cases where it's not available, so we tolerate ImportError.\n    try:\n        import google.auth.app_engine as app_engine\n    except ImportError:\n        return None, None\n\n    try:\n        credentials = app_engine.Credentials()\n        project_id = app_engine.get_project_id()\n        return credentials, project_id\n    except EnvironmentError:\n        return None, None\n\n\ndef _get_gce_credentials(request=None):\n    \"\"\"Gets credentials and project ID from the GCE Metadata Service.\"\"\"\n    # Ping requires a transport, but we want application default credentials\n    # to require no arguments. So, we'll use the _http_client transport which\n    # uses http.client. This is only acceptable because the metadata server\n    # doesn't do SSL and never requires proxies.\n\n    # While this library is normally bundled with compute_engine, there are\n    # some cases where it's not available, so we tolerate ImportError.\n    try:\n        from google.auth import compute_engine\n        from google.auth.compute_engine import _metadata\n    except ImportError:\n        return None, None\n\n    if request is None:\n        request = google.auth.transport._http_client.Request()\n\n    if _metadata.ping(request=request):\n        # Get the project ID.\n        try:\n            project_id = _metadata.get_project_id(request=request)\n        except exceptions.TransportError:\n            project_id = None\n\n        return compute_engine.Credentials(), project_id\n    else:\n        return None, None\n\n\ndef default(scopes=None, request=None, quota_project_id=None):\n    \"\"\"Gets the default credentials for the current environment.\n\n    `Application Default Credentials`_ provides an easy way to obtain\n    credentials to call Google APIs for server-to-server or local applications.\n    This function acquires credentials from the environment in the following\n    order:\n\n    1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set\n       to the path of a valid service account JSON private key file, then it is\n       loaded and returned. The project ID returned is the project ID defined\n       in the service account file if available (some older files do not\n       contain project ID information).\n    2. If the `Google Cloud SDK`_ is installed and has application default\n       credentials set they are loaded and returned.\n\n       To enable application default credentials with the Cloud SDK run::\n\n            gcloud auth application-default login\n\n       If the Cloud SDK has an active project, the project ID is returned. The\n       active project can be set using::\n\n            gcloud config set project\n\n    3. If the application is running in the `App Engine standard environment`_\n       then the credentials and project ID from the `App Identity Service`_\n       are used.\n    4. If the application is running in `Compute Engine`_ or the\n       `App Engine flexible environment`_ then the credentials and project ID\n       are obtained from the `Metadata Service`_.\n    5. If no credentials are found,\n       :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.\n\n    .. _Application Default Credentials: https://developers.google.com\\\n            /identity/protocols/application-default-credentials\n    .. _Google Cloud SDK: https://cloud.google.com/sdk\n    .. _App Engine standard environment: https://cloud.google.com/appengine\n    .. _App Identity Service: https://cloud.google.com/appengine/docs/python\\\n            /appidentity/\n    .. _Compute Engine: https://cloud.google.com/compute\n    .. _App Engine flexible environment: https://cloud.google.com\\\n            /appengine/flexible\n    .. _Metadata Service: https://cloud.google.com/compute/docs\\\n            /storing-retrieving-metadata\n\n    Example::\n\n        import google.auth\n\n        credentials, project_id = google.auth.default()\n\n    Args:\n        scopes (Sequence[str]): The list of scopes for the credentials. If\n            specified, the credentials will automatically be scoped if\n            necessary.\n        request (google.auth.transport.Request): An object used to make\n            HTTP requests. This is used to detect whether the application\n            is running on Compute Engine. If not specified, then it will\n            use the standard library http client to make requests.\n        quota_project_id (Optional[str]):  The project ID used for\n            quota and billing.\n    Returns:\n        Tuple[~google.auth.credentials.Credentials, Optional[str]]:\n            the current environment's credentials and project ID. Project ID\n            may be None, which indicates that the Project ID could not be\n            ascertained from the environment.\n\n    Raises:\n        ~google.auth.exceptions.DefaultCredentialsError:\n            If no credentials were found, or if the credentials found were\n            invalid.\n    \"\"\"\n    from google.auth.credentials import with_scopes_if_required\n\n    explicit_project_id = os.environ.get(\n        environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)\n    )\n\n    checkers = (\n        _get_explicit_environ_credentials,\n        _get_gcloud_sdk_credentials,\n        _get_gae_credentials,\n        lambda: _get_gce_credentials(request),\n    )\n\n    for checker in checkers:\n        credentials, project_id = checker()\n        if credentials is not None:\n            credentials = with_scopes_if_required(credentials, scopes)\n            if quota_project_id:\n                credentials = credentials.with_quota_project(quota_project_id)\n\n            effective_project_id = explicit_project_id or project_id\n            if not effective_project_id:\n                _LOGGER.warning(\n                    \"No project ID could be determined. Consider running \"\n                    \"`gcloud config set project` or setting the %s \"\n                    \"environment variable\",\n                    environment_vars.PROJECT,\n                )\n            return credentials, effective_project_id\n\n    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)\n", "path": "google/auth/_default.py"}]}