We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Setting GOOGLE_APPLICATION_CREDENTIALS to empty string throws an error
I would expect an empty environment variable to act identically to an unset environment variable.

Reported by @parthea

If I set my GOOGLE_APPLICATION_CREDENTIALS environment variable to an empty string, I receive an exception instead of the local user web authentication flow. Is it expected?

```
tony@tonypc:~/pydata-pandas-gbq/pandas_gbq/tests$ export GOOGLE_APPLICATION_CREDENTIALS=''
tony@tonypc:~/pydata-pandas-gbq/pandas_gbq/tests$ pytest test_gbq.py::TestGBQConnectorIntegrationWithLocalUserAccountAuth -v -r s . --maxfail=1
============================= test session starts ==============================
platform linux2 -- Python 2.7.12, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- /home/tony/miniconda2/bin/python
cachedir: ../../.cache
rootdir: /home/tony/pydata-pandas-gbq, inifile: 
plugins: cov-2.4.0
collected 100 items 

test_gbq.py::TestGBQConnectorIntegrationWithLocalUserAccountAuth::test_should_be_able_to_make_a_connector ERROR

==================================== ERRORS ====================================
 ERROR at setup of TestGBQConnectorIntegrationWithLocalUserAccountAuth.test_should_be_able_to_make_a_connector 

self = <pandas_gbq.tests.test_gbq.TestGBQConnectorIntegrationWithLocalUserAccountAuth object at 0x7f2bbecf6490>
method = <bound method TestGBQConnectorIntegrationWithLocalUserAccountAuth.test_should_....TestGBQConnectorIntegrationWithLocalUserAccountAuth object at 0x7f2bbecf6490>>

    def setup_method(self, method):
        _setup_common()
        _skip_if_no_project_id()
        _skip_local_auth_if_in_travis_env()
    
>       self.sut = gbq.GbqConnector(_get_project_id(), auth_local_webserver=True)

test_gbq.py:268: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
../gbq.py:174: in __init__
    auth_local_webserver=auth_local_webserver)
../gbq.py:182: in get_credentials
    credentials = self.get_application_default_credentials()
../gbq.py:212: in get_application_default_credentials
    credentials, _ = google.auth.default(scopes=[self.scope])
../../../miniconda2/lib/python2.7/site-packages/google/auth/_default.py:277: in default
    credentials, project_id = checker()
../../../miniconda2/lib/python2.7/site-packages/google/auth/_default.py:138: in _get_explicit_environ_credentials
    os.environ[environment_vars.CREDENTIALS])
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

filename = ''

    def _load_credentials_from_file(filename):
        """Loads credentials from a file.
    
        The credentials file must be a service account key or stored authorized
        user credentials.
    
        Args:
            filename (str): The full path to the credentials file.
    
        Returns:
            Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
                credentials and the project ID. Authorized user credentials do not
                have the project ID information.
    
        Raises:
            google.auth.exceptions.DefaultCredentialsError: if the file is in the
                wrong format.
        """
>       with io.open(filename, 'r') as file_obj:
E       IOError: [Errno 2] No such file or directory: ''

../../../miniconda2/lib/python2.7/site-packages/google/auth/_default.py:63: IOError
!!!!!!!!!!!!!!!!!!!! Interrupted: stopping after 1 failures !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.61 seconds ============================
```

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

{"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@@ -58,8 +58,12 @@\n \n     Raises:\n         google.auth.exceptions.DefaultCredentialsError: if the file is in the\n-            wrong format.\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     with io.open(filename, 'r') as file_obj:\n         try:\n             info = json.load(file_obj)\n", "issue": "Setting GOOGLE_APPLICATION_CREDENTIALS to empty string throws an error\nI would expect an empty environment variable to act identically to an unset environment variable.\r\n\r\nReported by @parthea\r\n\r\nIf I set my GOOGLE_APPLICATION_CREDENTIALS environment variable to an empty string, I receive an exception instead of the local user web authentication flow. Is it expected?\r\n\r\n```\r\ntony@tonypc:~/pydata-pandas-gbq/pandas_gbq/tests$ export GOOGLE_APPLICATION_CREDENTIALS=''\r\ntony@tonypc:~/pydata-pandas-gbq/pandas_gbq/tests$ pytest test_gbq.py::TestGBQConnectorIntegrationWithLocalUserAccountAuth -v -r s . --maxfail=1\r\n============================= test session starts ==============================\r\nplatform linux2 -- Python 2.7.12, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- /home/tony/miniconda2/bin/python\r\ncachedir: ../../.cache\r\nrootdir: /home/tony/pydata-pandas-gbq, inifile: \r\nplugins: cov-2.4.0\r\ncollected 100 items \r\n\r\ntest_gbq.py::TestGBQConnectorIntegrationWithLocalUserAccountAuth::test_should_be_able_to_make_a_connector ERROR\r\n\r\n==================================== ERRORS ====================================\r\n ERROR at setup of TestGBQConnectorIntegrationWithLocalUserAccountAuth.test_should_be_able_to_make_a_connector \r\n\r\nself = <pandas_gbq.tests.test_gbq.TestGBQConnectorIntegrationWithLocalUserAccountAuth object at 0x7f2bbecf6490>\r\nmethod = <bound method TestGBQConnectorIntegrationWithLocalUserAccountAuth.test_should_....TestGBQConnectorIntegrationWithLocalUserAccountAuth object at 0x7f2bbecf6490>>\r\n\r\n    def setup_method(self, method):\r\n        _setup_common()\r\n        _skip_if_no_project_id()\r\n        _skip_local_auth_if_in_travis_env()\r\n    \r\n>       self.sut = gbq.GbqConnector(_get_project_id(), auth_local_webserver=True)\r\n\r\ntest_gbq.py:268: \r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\n../gbq.py:174: in __init__\r\n    auth_local_webserver=auth_local_webserver)\r\n../gbq.py:182: in get_credentials\r\n    credentials = self.get_application_default_credentials()\r\n../gbq.py:212: in get_application_default_credentials\r\n    credentials, _ = google.auth.default(scopes=[self.scope])\r\n../../../miniconda2/lib/python2.7/site-packages/google/auth/_default.py:277: in default\r\n    credentials, project_id = checker()\r\n../../../miniconda2/lib/python2.7/site-packages/google/auth/_default.py:138: in _get_explicit_environ_credentials\r\n    os.environ[environment_vars.CREDENTIALS])\r\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \r\n\r\nfilename = ''\r\n\r\n    def _load_credentials_from_file(filename):\r\n        \"\"\"Loads credentials from a file.\r\n    \r\n        The credentials file must be a service account key or stored authorized\r\n        user credentials.\r\n    \r\n        Args:\r\n            filename (str): The full path to the credentials file.\r\n    \r\n        Returns:\r\n            Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded\r\n                credentials and the project ID. Authorized user credentials do not\r\n                have the project ID information.\r\n    \r\n        Raises:\r\n            google.auth.exceptions.DefaultCredentialsError: if the file is in the\r\n                wrong format.\r\n        \"\"\"\r\n>       with io.open(filename, 'r') as file_obj:\r\nE       IOError: [Errno 2] No such file or directory: ''\r\n\r\n../../../miniconda2/lib/python2.7/site-packages/google/auth/_default.py:63: IOError\r\n!!!!!!!!!!!!!!!!!!!! Interrupted: stopping after 1 failures !!!!!!!!!!!!!!!!!!!!\r\n=========================== 1 error in 0.61 seconds ============================\r\n```\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\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 credential and re-run the application. For more\ninformation, please see\nhttps://developers.google.com/accounts/docs/application-default-credentials.\n\"\"\".format(env=environment_vars.CREDENTIALS).strip()\n\n\ndef _load_credentials_from_file(filename):\n    \"\"\"Loads 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\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.\n    \"\"\"\n    with io.open(filename, 'r') as file_obj:\n        try:\n            info = json.load(file_obj)\n        except ValueError as exc:\n            raise exceptions.DefaultCredentialsError(\n                'File {} is not a valid json file.'.format(filename), 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.auth import _cloud_sdk\n\n        try:\n            credentials = _cloud_sdk.load_authorized_user_credentials(info)\n        except ValueError as exc:\n            raise exceptions.DefaultCredentialsError(\n                'Failed to load authorized user credentials from {}'.format(\n                    filename), exc)\n        # Authorized user credentials do not contain the project ID.\n        return credentials, None\n\n    elif credential_type == _SERVICE_ACCOUNT_TYPE:\n        from google.oauth2 import service_account\n\n        try:\n            credentials = (\n                service_account.Credentials.from_service_account_info(info))\n        except ValueError as exc:\n            raise exceptions.DefaultCredentialsError(\n                'Failed to load service account credentials from {}'.format(\n                    filename), 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\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 = (\n        _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(\n        credentials_filename)\n\n    if not project_id:\n        project_id = _cloud_sdk.get_project_id()\n\n    if not project_id:\n        _LOGGER.warning(\n            'No project ID could be determined from the Cloud SDK '\n            'configuration. Consider running `gcloud config set project` or '\n            'setting the %s environment variable', environment_vars.PROJECT)\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        if not project_id:\n            _LOGGER.warning(\n                'No project ID could be determined from the credentials at %s '\n                'Consider setting the %s environment variable',\n                environment_vars.CREDENTIALS, environment_vars.PROJECT)\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    from google.auth import app_engine\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    from google.auth import compute_engine\n    from google.auth.compute_engine import _metadata\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            _LOGGER.warning(\n                'No project ID could be determined from the Compute Engine '\n                'metadata service. Consider setting the %s environment '\n                'variable.', environment_vars.PROJECT)\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):\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\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,\n        os.environ.get(environment_vars.LEGACY_PROJECT))\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    for checker in checkers:\n        credentials, project_id = checker()\n        if credentials is not None:\n            credentials = with_scopes_if_required(credentials, scopes)\n            return credentials, explicit_project_id or 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\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 credential and re-run the application. For more\ninformation, please see\nhttps://developers.google.com/accounts/docs/application-default-credentials.\n\"\"\".format(env=environment_vars.CREDENTIALS).strip()\n\n\ndef _load_credentials_from_file(filename):\n    \"\"\"Loads 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\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    with io.open(filename, 'r') as file_obj:\n        try:\n            info = json.load(file_obj)\n        except ValueError as exc:\n            raise exceptions.DefaultCredentialsError(\n                'File {} is not a valid json file.'.format(filename), 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.auth import _cloud_sdk\n\n        try:\n            credentials = _cloud_sdk.load_authorized_user_credentials(info)\n        except ValueError as exc:\n            raise exceptions.DefaultCredentialsError(\n                'Failed to load authorized user credentials from {}'.format(\n                    filename), exc)\n        # Authorized user credentials do not contain the project ID.\n        return credentials, None\n\n    elif credential_type == _SERVICE_ACCOUNT_TYPE:\n        from google.oauth2 import service_account\n\n        try:\n            credentials = (\n                service_account.Credentials.from_service_account_info(info))\n        except ValueError as exc:\n            raise exceptions.DefaultCredentialsError(\n                'Failed to load service account credentials from {}'.format(\n                    filename), 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\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 = (\n        _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(\n        credentials_filename)\n\n    if not project_id:\n        project_id = _cloud_sdk.get_project_id()\n\n    if not project_id:\n        _LOGGER.warning(\n            'No project ID could be determined from the Cloud SDK '\n            'configuration. Consider running `gcloud config set project` or '\n            'setting the %s environment variable', environment_vars.PROJECT)\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        if not project_id:\n            _LOGGER.warning(\n                'No project ID could be determined from the credentials at %s '\n                'Consider setting the %s environment variable',\n                environment_vars.CREDENTIALS, environment_vars.PROJECT)\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    from google.auth import app_engine\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    from google.auth import compute_engine\n    from google.auth.compute_engine import _metadata\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            _LOGGER.warning(\n                'No project ID could be determined from the Compute Engine '\n                'metadata service. Consider setting the %s environment '\n                'variable.', environment_vars.PROJECT)\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):\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\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,\n        os.environ.get(environment_vars.LEGACY_PROJECT))\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    for checker in checkers:\n        credentials, project_id = checker()\n        if credentials is not None:\n            credentials = with_scopes_if_required(credentials, scopes)\n            return credentials, explicit_project_id or project_id\n\n    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)\n", "path": "google/auth/_default.py"}]}