We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Support `GCLOUD_PROJECT` environment variable


--- 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/environment_vars.py`
Content:
```
1 # Copyright 2016 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 """Environment variables used by :mod:`google.auth`."""
16 
17 
18 PROJECT = 'GOOGLE_CLOUD_PROJECT'
19 """Environment variable defining default project.
20 
21 This used by :func:`google.auth.default` to explicitly set a project ID. This
22 environment variable is also used by the Google Cloud Python Library.
23 """
24 
25 CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'
26 """Environment variable defining the location of Google application default
27 credentials."""
28 
29 # The environment variable name which can replace ~/.config if set.
30 CLOUD_SDK_CONFIG_DIR = 'CLOUDSDK_CONFIG'
31 """Environment variable defines the location of Google Cloud SDK's config
32 files."""
33
```

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

{"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@@ -254,7 +254,9 @@\n             If no credentials were found, or if the credentials found were\n             invalid.\n     \"\"\"\n-    explicit_project_id = os.environ.get(environment_vars.PROJECT)\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,\ndiff --git a/google/auth/environment_vars.py b/google/auth/environment_vars.py\n--- a/google/auth/environment_vars.py\n+++ b/google/auth/environment_vars.py\n@@ -22,6 +22,13 @@\n environment variable is also used by the Google Cloud Python Library.\n \"\"\"\n \n+LEGACY_PROJECT = 'GCLOUD_PROJECT'\n+\"\"\"Previously used environment variable defining the default project.\n+\n+This environment variable is used instead of the current one in some\n+situations (such as Google App Engine).\n+\"\"\"\n+\n CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'\n \"\"\"Environment variable defining the location of Google application default\n credentials.\"\"\"\n", "issue": "Support `GCLOUD_PROJECT` environment variable\n\n", "before_files": [{"content": "# Copyright 2016 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\"\"\"Environment variables used by :mod:`google.auth`.\"\"\"\n\n\nPROJECT = 'GOOGLE_CLOUD_PROJECT'\n\"\"\"Environment variable defining default project.\n\nThis used by :func:`google.auth.default` to explicitly set a project ID. This\nenvironment variable is also used by the Google Cloud Python Library.\n\"\"\"\n\nCREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'\n\"\"\"Environment variable defining the location of Google application default\ncredentials.\"\"\"\n\n# The environment variable name which can replace ~/.config if set.\nCLOUD_SDK_CONFIG_DIR = 'CLOUDSDK_CONFIG'\n\"\"\"Environment variable defines the location of Google Cloud SDK's config\nfiles.\"\"\"\n", "path": "google/auth/environment_vars.py"}, {"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 _cloud_sdk\nfrom google.auth import app_engine\nfrom google.auth import compute_engine\nfrom google.auth import environment_vars\nfrom google.auth import exceptions\nfrom google.auth.compute_engine import _metadata\nimport google.auth.transport._http_client\nfrom google.oauth2 import service_account\nimport google.oauth2.credentials\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        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        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    # 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    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    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(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        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    explicit_project_id = os.environ.get(environment_vars.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            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 2016 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\"\"\"Environment variables used by :mod:`google.auth`.\"\"\"\n\n\nPROJECT = 'GOOGLE_CLOUD_PROJECT'\n\"\"\"Environment variable defining default project.\n\nThis used by :func:`google.auth.default` to explicitly set a project ID. This\nenvironment variable is also used by the Google Cloud Python Library.\n\"\"\"\n\nLEGACY_PROJECT = 'GCLOUD_PROJECT'\n\"\"\"Previously used environment variable defining the default project.\n\nThis environment variable is used instead of the current one in some\nsituations (such as Google App Engine).\n\"\"\"\n\nCREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'\n\"\"\"Environment variable defining the location of Google application default\ncredentials.\"\"\"\n\n# The environment variable name which can replace ~/.config if set.\nCLOUD_SDK_CONFIG_DIR = 'CLOUDSDK_CONFIG'\n\"\"\"Environment variable defines the location of Google Cloud SDK's config\nfiles.\"\"\"\n", "path": "google/auth/environment_vars.py"}, {"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 _cloud_sdk\nfrom google.auth import app_engine\nfrom google.auth import compute_engine\nfrom google.auth import environment_vars\nfrom google.auth import exceptions\nfrom google.auth.compute_engine import _metadata\nimport google.auth.transport._http_client\nfrom google.oauth2 import service_account\nimport google.oauth2.credentials\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        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        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    # 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    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    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(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        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    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            return credentials, explicit_project_id or project_id\n\n    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)\n", "path": "google/auth/_default.py"}]}