google-auth 1.21.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. google/auth/__init__.py +26 -0
  2. google/auth/_cloud_sdk.py +152 -0
  3. google/auth/_default.py +354 -0
  4. google/auth/_helpers.py +232 -0
  5. google/auth/_oauth2client.py +169 -0
  6. google/auth/_service_account_info.py +74 -0
  7. google/auth/app_engine.py +168 -0
  8. google/auth/compute_engine/__init__.py +21 -0
  9. google/auth/compute_engine/_metadata.py +257 -0
  10. google/auth/compute_engine/credentials.py +392 -0
  11. google/auth/credentials.py +350 -0
  12. google/auth/crypt/__init__.py +100 -0
  13. google/auth/crypt/_cryptography_rsa.py +149 -0
  14. google/auth/crypt/_helpers.py +0 -0
  15. google/auth/crypt/_python_rsa.py +173 -0
  16. google/auth/crypt/base.py +131 -0
  17. google/auth/crypt/es256.py +160 -0
  18. google/auth/crypt/rsa.py +30 -0
  19. google/auth/environment_vars.py +61 -0
  20. google/auth/exceptions.py +45 -0
  21. google/auth/iam.py +100 -0
  22. google/auth/impersonated_credentials.py +398 -0
  23. google/auth/jwt.py +842 -0
  24. google/auth/transport/__init__.py +97 -0
  25. google/auth/transport/_http_client.py +115 -0
  26. google/auth/transport/_mtls_helper.py +250 -0
  27. google/auth/transport/grpc.py +334 -0
  28. google/auth/transport/mtls.py +102 -0
  29. google/auth/transport/requests.py +521 -0
  30. google/auth/transport/urllib3.py +426 -0
  31. google/oauth2/__init__.py +15 -0
  32. google/oauth2/_client.py +259 -0
  33. google/oauth2/credentials.py +360 -0
  34. google/oauth2/id_token.py +266 -0
  35. google/oauth2/service_account.py +604 -0
  36. google_auth-1.21.0-py3.8-nspkg.pth +1 -0
  37. google_auth-1.21.0.dist-info/LICENSE +201 -0
  38. google_auth-1.21.0.dist-info/METADATA +98 -0
  39. google_auth-1.21.0.dist-info/RECORD +42 -0
  40. google_auth-1.21.0.dist-info/WHEEL +6 -0
  41. google_auth-1.21.0.dist-info/namespace_packages.txt +1 -0
  42. google_auth-1.21.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,26 @@
1
+ # Copyright 2016 Google LLC
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
+ """Google Auth Library for Python."""
16
+
17
+ import logging
18
+
19
+ from google.auth._default import default, load_credentials_from_file
20
+
21
+
22
+ __all__ = ["default", "load_credentials_from_file"]
23
+
24
+
25
+ # Set default logging handler to avoid "No handler found" warnings.
26
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -0,0 +1,152 @@
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
+ """Helpers for reading the Google Cloud SDK's configuration."""
16
+
17
+ import json
18
+ import os
19
+ import subprocess
20
+
21
+ import six
22
+
23
+ from google.auth import environment_vars
24
+ from google.auth import exceptions
25
+
26
+
27
+ # The ~/.config subdirectory containing gcloud credentials.
28
+ _CONFIG_DIRECTORY = "gcloud"
29
+ # Windows systems store config at %APPDATA%\gcloud
30
+ _WINDOWS_CONFIG_ROOT_ENV_VAR = "APPDATA"
31
+ # The name of the file in the Cloud SDK config that contains default
32
+ # credentials.
33
+ _CREDENTIALS_FILENAME = "application_default_credentials.json"
34
+ # The name of the Cloud SDK shell script
35
+ _CLOUD_SDK_POSIX_COMMAND = "gcloud"
36
+ _CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd"
37
+ # The command to get the Cloud SDK configuration
38
+ _CLOUD_SDK_CONFIG_COMMAND = ("config", "config-helper", "--format", "json")
39
+ # The command to get google user access token
40
+ _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND = ("auth", "print-access-token")
41
+ # Cloud SDK's application-default client ID
42
+ CLOUD_SDK_CLIENT_ID = (
43
+ "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"
44
+ )
45
+
46
+
47
+ def get_config_path():
48
+ """Returns the absolute path the the Cloud SDK's configuration directory.
49
+
50
+ Returns:
51
+ str: The Cloud SDK config path.
52
+ """
53
+ # If the path is explicitly set, return that.
54
+ try:
55
+ return os.environ[environment_vars.CLOUD_SDK_CONFIG_DIR]
56
+ except KeyError:
57
+ pass
58
+
59
+ # Non-windows systems store this at ~/.config/gcloud
60
+ if os.name != "nt":
61
+ return os.path.join(os.path.expanduser("~"), ".config", _CONFIG_DIRECTORY)
62
+ # Windows systems store config at %APPDATA%\gcloud
63
+ else:
64
+ try:
65
+ return os.path.join(
66
+ os.environ[_WINDOWS_CONFIG_ROOT_ENV_VAR], _CONFIG_DIRECTORY
67
+ )
68
+ except KeyError:
69
+ # This should never happen unless someone is really
70
+ # messing with things, but we'll cover the case anyway.
71
+ drive = os.environ.get("SystemDrive", "C:")
72
+ return os.path.join(drive, "\\", _CONFIG_DIRECTORY)
73
+
74
+
75
+ def get_application_default_credentials_path():
76
+ """Gets the path to the application default credentials file.
77
+
78
+ The path may or may not exist.
79
+
80
+ Returns:
81
+ str: The full path to application default credentials.
82
+ """
83
+ config_path = get_config_path()
84
+ return os.path.join(config_path, _CREDENTIALS_FILENAME)
85
+
86
+
87
+ def get_project_id():
88
+ """Gets the project ID from the Cloud SDK.
89
+
90
+ Returns:
91
+ Optional[str]: The project ID.
92
+ """
93
+ if os.name == "nt":
94
+ command = _CLOUD_SDK_WINDOWS_COMMAND
95
+ else:
96
+ command = _CLOUD_SDK_POSIX_COMMAND
97
+
98
+ try:
99
+ output = subprocess.check_output(
100
+ (command,) + _CLOUD_SDK_CONFIG_COMMAND, stderr=subprocess.STDOUT
101
+ )
102
+ except (subprocess.CalledProcessError, OSError, IOError):
103
+ return None
104
+
105
+ try:
106
+ configuration = json.loads(output.decode("utf-8"))
107
+ except ValueError:
108
+ return None
109
+
110
+ try:
111
+ return configuration["configuration"]["properties"]["core"]["project"]
112
+ except KeyError:
113
+ return None
114
+
115
+
116
+ def get_auth_access_token(account=None):
117
+ """Load user access token with the ``gcloud auth print-access-token`` command.
118
+
119
+ Args:
120
+ account (Optional[str]): Account to get the access token for. If not
121
+ specified, the current active account will be used.
122
+
123
+ Returns:
124
+ str: The user access token.
125
+
126
+ Raises:
127
+ google.auth.exceptions.UserAccessTokenError: if failed to get access
128
+ token from gcloud.
129
+ """
130
+ if os.name == "nt":
131
+ command = _CLOUD_SDK_WINDOWS_COMMAND
132
+ else:
133
+ command = _CLOUD_SDK_POSIX_COMMAND
134
+
135
+ try:
136
+ if account:
137
+ command = (
138
+ (command,)
139
+ + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
140
+ + ("--account=" + account,)
141
+ )
142
+ else:
143
+ command = (command,) + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
144
+
145
+ access_token = subprocess.check_output(command, stderr=subprocess.STDOUT)
146
+ # remove the trailing "\n"
147
+ return access_token.decode("utf-8").strip()
148
+ except (subprocess.CalledProcessError, OSError, IOError) as caught_exc:
149
+ new_exc = exceptions.UserAccessTokenError(
150
+ "Failed to obtain access token", caught_exc
151
+ )
152
+ six.raise_from(new_exc, caught_exc)
@@ -0,0 +1,354 @@
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
+ )
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 quota_project_id:
125
+ credentials = credentials.with_quota_project(quota_project_id)
126
+ if not credentials.quota_project_id:
127
+ _warn_about_problematic_credentials(credentials)
128
+ return credentials, None
129
+
130
+ elif credential_type == _SERVICE_ACCOUNT_TYPE:
131
+ from google.oauth2 import service_account
132
+
133
+ try:
134
+ credentials = service_account.Credentials.from_service_account_info(
135
+ info, scopes=scopes
136
+ )
137
+ except ValueError as caught_exc:
138
+ msg = "Failed to load service account credentials from {}".format(filename)
139
+ new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
140
+ six.raise_from(new_exc, caught_exc)
141
+ if quota_project_id:
142
+ credentials = credentials.with_quota_project(quota_project_id)
143
+ return credentials, info.get("project_id")
144
+
145
+ else:
146
+ raise exceptions.DefaultCredentialsError(
147
+ "The file {file} does not have a valid type. "
148
+ "Type is {type}, expected one of {valid_types}.".format(
149
+ file=filename, type=credential_type, valid_types=_VALID_TYPES
150
+ )
151
+ )
152
+
153
+
154
+ def _get_gcloud_sdk_credentials():
155
+ """Gets the credentials and project ID from the Cloud SDK."""
156
+ from google.auth import _cloud_sdk
157
+
158
+ _LOGGER.debug("Checking Cloud SDK credentials as part of auth process...")
159
+
160
+ # Check if application default credentials exist.
161
+ credentials_filename = _cloud_sdk.get_application_default_credentials_path()
162
+
163
+ if not os.path.isfile(credentials_filename):
164
+ _LOGGER.debug("Cloud SDK credentials not found on disk; not using them")
165
+ return None, None
166
+
167
+ credentials, project_id = load_credentials_from_file(credentials_filename)
168
+
169
+ if not project_id:
170
+ project_id = _cloud_sdk.get_project_id()
171
+
172
+ return credentials, project_id
173
+
174
+
175
+ def _get_explicit_environ_credentials():
176
+ """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
177
+ variable."""
178
+ explicit_file = os.environ.get(environment_vars.CREDENTIALS)
179
+
180
+ _LOGGER.debug(
181
+ "Checking %s for explicit credentials as part of auth process...", explicit_file
182
+ )
183
+
184
+ if explicit_file is not None:
185
+ credentials, project_id = load_credentials_from_file(
186
+ os.environ[environment_vars.CREDENTIALS]
187
+ )
188
+
189
+ return credentials, project_id
190
+
191
+ else:
192
+ return None, None
193
+
194
+
195
+ def _get_gae_credentials():
196
+ """Gets Google App Engine App Identity credentials and project ID."""
197
+ # While this library is normally bundled with app_engine, there are
198
+ # some cases where it's not available, so we tolerate ImportError.
199
+ try:
200
+ _LOGGER.debug("Checking for App Engine runtime as part of auth process...")
201
+ import google.auth.app_engine as app_engine
202
+ except ImportError:
203
+ _LOGGER.warning("Import of App Engine auth library failed.")
204
+ return None, None
205
+
206
+ try:
207
+ credentials = app_engine.Credentials()
208
+ project_id = app_engine.get_project_id()
209
+ return credentials, project_id
210
+ except EnvironmentError:
211
+ _LOGGER.debug(
212
+ "No App Engine library was found so cannot authentication via App Engine Identity Credentials."
213
+ )
214
+ return None, None
215
+
216
+
217
+ def _get_gce_credentials(request=None):
218
+ """Gets credentials and project ID from the GCE Metadata Service."""
219
+ # Ping requires a transport, but we want application default credentials
220
+ # to require no arguments. So, we'll use the _http_client transport which
221
+ # uses http.client. This is only acceptable because the metadata server
222
+ # doesn't do SSL and never requires proxies.
223
+
224
+ # While this library is normally bundled with compute_engine, there are
225
+ # some cases where it's not available, so we tolerate ImportError.
226
+ try:
227
+ from google.auth import compute_engine
228
+ from google.auth.compute_engine import _metadata
229
+ except ImportError:
230
+ _LOGGER.warning("Import of Compute Engine auth library failed.")
231
+ return None, None
232
+
233
+ if request is None:
234
+ request = google.auth.transport._http_client.Request()
235
+
236
+ if _metadata.ping(request=request):
237
+ # Get the project ID.
238
+ try:
239
+ project_id = _metadata.get_project_id(request=request)
240
+ except exceptions.TransportError:
241
+ project_id = None
242
+
243
+ return compute_engine.Credentials(), project_id
244
+ else:
245
+ _LOGGER.warning(
246
+ "Authentication failed using Compute Engine authentication due to unavailable metadata server."
247
+ )
248
+ return None, None
249
+
250
+
251
+ def default(scopes=None, request=None, quota_project_id=None):
252
+ """Gets the default credentials for the current environment.
253
+
254
+ `Application Default Credentials`_ provides an easy way to obtain
255
+ credentials to call Google APIs for server-to-server or local applications.
256
+ This function acquires credentials from the environment in the following
257
+ order:
258
+
259
+ 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
260
+ to the path of a valid service account JSON private key file, then it is
261
+ loaded and returned. The project ID returned is the project ID defined
262
+ in the service account file if available (some older files do not
263
+ contain project ID information).
264
+ 2. If the `Google Cloud SDK`_ is installed and has application default
265
+ credentials set they are loaded and returned.
266
+
267
+ To enable application default credentials with the Cloud SDK run::
268
+
269
+ gcloud auth application-default login
270
+
271
+ If the Cloud SDK has an active project, the project ID is returned. The
272
+ active project can be set using::
273
+
274
+ gcloud config set project
275
+
276
+ 3. If the application is running in the `App Engine standard environment`_
277
+ then the credentials and project ID from the `App Identity Service`_
278
+ are used.
279
+ 4. If the application is running in `Compute Engine`_ or the
280
+ `App Engine flexible environment`_ then the credentials and project ID
281
+ are obtained from the `Metadata Service`_.
282
+ 5. If no credentials are found,
283
+ :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
284
+
285
+ .. _Application Default Credentials: https://developers.google.com\
286
+ /identity/protocols/application-default-credentials
287
+ .. _Google Cloud SDK: https://cloud.google.com/sdk
288
+ .. _App Engine standard environment: https://cloud.google.com/appengine
289
+ .. _App Identity Service: https://cloud.google.com/appengine/docs/python\
290
+ /appidentity/
291
+ .. _Compute Engine: https://cloud.google.com/compute
292
+ .. _App Engine flexible environment: https://cloud.google.com\
293
+ /appengine/flexible
294
+ .. _Metadata Service: https://cloud.google.com/compute/docs\
295
+ /storing-retrieving-metadata
296
+
297
+ Example::
298
+
299
+ import google.auth
300
+
301
+ credentials, project_id = google.auth.default()
302
+
303
+ Args:
304
+ scopes (Sequence[str]): The list of scopes for the credentials. If
305
+ specified, the credentials will automatically be scoped if
306
+ necessary.
307
+ request (google.auth.transport.Request): An object used to make
308
+ HTTP requests. This is used to detect whether the application
309
+ is running on Compute Engine. If not specified, then it will
310
+ use the standard library http client to make requests.
311
+ quota_project_id (Optional[str]): The project ID used for
312
+ quota and billing.
313
+ Returns:
314
+ Tuple[~google.auth.credentials.Credentials, Optional[str]]:
315
+ the current environment's credentials and project ID. Project ID
316
+ may be None, which indicates that the Project ID could not be
317
+ ascertained from the environment.
318
+
319
+ Raises:
320
+ ~google.auth.exceptions.DefaultCredentialsError:
321
+ If no credentials were found, or if the credentials found were
322
+ invalid.
323
+ """
324
+ from google.auth.credentials import with_scopes_if_required
325
+
326
+ explicit_project_id = os.environ.get(
327
+ environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT)
328
+ )
329
+
330
+ checkers = (
331
+ _get_explicit_environ_credentials,
332
+ _get_gcloud_sdk_credentials,
333
+ _get_gae_credentials,
334
+ lambda: _get_gce_credentials(request),
335
+ )
336
+
337
+ for checker in checkers:
338
+ credentials, project_id = checker()
339
+ if credentials is not None:
340
+ credentials = with_scopes_if_required(credentials, scopes)
341
+ if quota_project_id:
342
+ credentials = credentials.with_quota_project(quota_project_id)
343
+
344
+ effective_project_id = explicit_project_id or project_id
345
+ if not effective_project_id:
346
+ _LOGGER.warning(
347
+ "No project ID could be determined. Consider running "
348
+ "`gcloud config set project` or setting the %s "
349
+ "environment variable",
350
+ environment_vars.PROJECT,
351
+ )
352
+ return credentials, effective_project_id
353
+
354
+ raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)