Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- lib/python3.10/site-packages/google/oauth2/__init__.py +36 -0
- lib/python3.10/site-packages/google/oauth2/_client.py +508 -0
- lib/python3.10/site-packages/google/oauth2/_client_async.py +286 -0
- lib/python3.10/site-packages/google/oauth2/_id_token_async.py +285 -0
- lib/python3.10/site-packages/google/oauth2/_reauth_async.py +328 -0
- lib/python3.10/site-packages/google/oauth2/challenges.py +281 -0
- lib/python3.10/site-packages/google/oauth2/credentials.py +614 -0
- lib/python3.10/site-packages/google/oauth2/gdch_credentials.py +251 -0
- lib/python3.10/site-packages/google/oauth2/id_token.py +358 -0
- lib/python3.10/site-packages/google/oauth2/py.typed +2 -0
- lib/python3.10/site-packages/google/oauth2/reauth.py +369 -0
- lib/python3.10/site-packages/google/oauth2/service_account.py +847 -0
- lib/python3.10/site-packages/google/oauth2/utils.py +168 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/INSTALLER +1 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/LICENSE.markdown-it +22 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/METADATA +205 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/RECORD +77 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/REQUESTED +0 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/WHEEL +4 -0
- lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/entry_points.txt +3 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Araguaina +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Argentina/Salta +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Argentina/Tucuman +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Asuncion +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Belem +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Boise +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Cambridge_Bay +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Cancun +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Dawson +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Dominica +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/El_Salvador +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Goose_Bay +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Grenada +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Hermosillo +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Knox +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Marengo +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Petersburg +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Tell_City +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vevay +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vincennes +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Winamac +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Indianapolis +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Iqaluit +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Jamaica +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Jujuy +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Juneau +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Kentucky/Louisville +0 -0
- lib/python3.10/site-packages/pytz/zoneinfo/America/Kentucky/Monticello +0 -0
lib/python3.10/site-packages/google/oauth2/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 OAuth 2.0 Library for Python."""
|
| 16 |
+
|
| 17 |
+
import sys
|
| 18 |
+
import warnings
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Python37DeprecationWarning(DeprecationWarning): # pragma: NO COVER
|
| 22 |
+
"""
|
| 23 |
+
Deprecation warning raised when Python 3.7 runtime is detected.
|
| 24 |
+
Python 3.7 support will be dropped after January 1, 2024.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# Checks if the current runtime is Python 3.7.
|
| 31 |
+
if sys.version_info.major == 3 and sys.version_info.minor == 7: # pragma: NO COVER
|
| 32 |
+
message = (
|
| 33 |
+
"After January 1, 2024, new releases of this library will drop support "
|
| 34 |
+
"for Python 3.7."
|
| 35 |
+
)
|
| 36 |
+
warnings.warn(message, Python37DeprecationWarning)
|
lib/python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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""OAuth 2.0 client.
|
| 16 |
+
|
| 17 |
+
This is a client for interacting with an OAuth 2.0 authorization server's
|
| 18 |
+
token endpoint.
|
| 19 |
+
|
| 20 |
+
For more information about the token endpoint, see
|
| 21 |
+
`Section 3.1 of rfc6749`_
|
| 22 |
+
|
| 23 |
+
.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import datetime
|
| 27 |
+
import http.client as http_client
|
| 28 |
+
import json
|
| 29 |
+
import urllib
|
| 30 |
+
|
| 31 |
+
from google.auth import _exponential_backoff
|
| 32 |
+
from google.auth import _helpers
|
| 33 |
+
from google.auth import credentials
|
| 34 |
+
from google.auth import exceptions
|
| 35 |
+
from google.auth import jwt
|
| 36 |
+
from google.auth import metrics
|
| 37 |
+
from google.auth import transport
|
| 38 |
+
|
| 39 |
+
_URLENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"
|
| 40 |
+
_JSON_CONTENT_TYPE = "application/json"
|
| 41 |
+
_JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
|
| 42 |
+
_REFRESH_GRANT_TYPE = "refresh_token"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _handle_error_response(response_data, retryable_error):
|
| 46 |
+
"""Translates an error response into an exception.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
response_data (Mapping | str): The decoded response data.
|
| 50 |
+
retryable_error Optional[bool]: A boolean indicating if an error is retryable.
|
| 51 |
+
Defaults to False.
|
| 52 |
+
|
| 53 |
+
Raises:
|
| 54 |
+
google.auth.exceptions.RefreshError: The errors contained in response_data.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
retryable_error = retryable_error if retryable_error else False
|
| 58 |
+
|
| 59 |
+
if isinstance(response_data, str):
|
| 60 |
+
raise exceptions.RefreshError(response_data, retryable=retryable_error)
|
| 61 |
+
try:
|
| 62 |
+
error_details = "{}: {}".format(
|
| 63 |
+
response_data["error"], response_data.get("error_description")
|
| 64 |
+
)
|
| 65 |
+
# If no details could be extracted, use the response data.
|
| 66 |
+
except (KeyError, ValueError):
|
| 67 |
+
error_details = json.dumps(response_data)
|
| 68 |
+
|
| 69 |
+
raise exceptions.RefreshError(
|
| 70 |
+
error_details, response_data, retryable=retryable_error
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _can_retry(status_code, response_data):
|
| 75 |
+
"""Checks if a request can be retried by inspecting the status code
|
| 76 |
+
and response body of the request.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
status_code (int): The response status code.
|
| 80 |
+
response_data (Mapping | str): The decoded response data.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
bool: True if the response is retryable. False otherwise.
|
| 84 |
+
"""
|
| 85 |
+
if status_code in transport.DEFAULT_RETRYABLE_STATUS_CODES:
|
| 86 |
+
return True
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
# For a failed response, response_body could be a string
|
| 90 |
+
error_desc = response_data.get("error_description") or ""
|
| 91 |
+
error_code = response_data.get("error") or ""
|
| 92 |
+
|
| 93 |
+
if not isinstance(error_code, str) or not isinstance(error_desc, str):
|
| 94 |
+
return False
|
| 95 |
+
|
| 96 |
+
# Per Oauth 2.0 RFC https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.2.1
|
| 97 |
+
# This is needed because a redirect will not return a 500 status code.
|
| 98 |
+
retryable_error_descriptions = {
|
| 99 |
+
"internal_failure",
|
| 100 |
+
"server_error",
|
| 101 |
+
"temporarily_unavailable",
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
if any(e in retryable_error_descriptions for e in (error_code, error_desc)):
|
| 105 |
+
return True
|
| 106 |
+
|
| 107 |
+
except AttributeError:
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _parse_expiry(response_data):
|
| 114 |
+
"""Parses the expiry field from a response into a datetime.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
response_data (Mapping): The JSON-parsed response data.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
Optional[datetime]: The expiration or ``None`` if no expiration was
|
| 121 |
+
specified.
|
| 122 |
+
"""
|
| 123 |
+
expires_in = response_data.get("expires_in", None)
|
| 124 |
+
|
| 125 |
+
if expires_in is not None:
|
| 126 |
+
# Some services do not respect the OAUTH2.0 RFC and send expires_in as a
|
| 127 |
+
# JSON String.
|
| 128 |
+
if isinstance(expires_in, str):
|
| 129 |
+
expires_in = int(expires_in)
|
| 130 |
+
|
| 131 |
+
return _helpers.utcnow() + datetime.timedelta(seconds=expires_in)
|
| 132 |
+
else:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _token_endpoint_request_no_throw(
|
| 137 |
+
request,
|
| 138 |
+
token_uri,
|
| 139 |
+
body,
|
| 140 |
+
access_token=None,
|
| 141 |
+
use_json=False,
|
| 142 |
+
can_retry=True,
|
| 143 |
+
headers=None,
|
| 144 |
+
**kwargs
|
| 145 |
+
):
|
| 146 |
+
"""Makes a request to the OAuth 2.0 authorization server's token endpoint.
|
| 147 |
+
This function doesn't throw on response errors.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
request (google.auth.transport.Request): A callable used to make
|
| 151 |
+
HTTP requests.
|
| 152 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 153 |
+
URI.
|
| 154 |
+
body (Mapping[str, str]): The parameters to send in the request body.
|
| 155 |
+
access_token (Optional(str)): The access token needed to make the request.
|
| 156 |
+
use_json (Optional(bool)): Use urlencoded format or json format for the
|
| 157 |
+
content type. The default value is False.
|
| 158 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 159 |
+
headers (Optional[Mapping[str, str]]): The headers for the request.
|
| 160 |
+
kwargs: Additional arguments passed on to the request method. The
|
| 161 |
+
kwargs will be passed to `requests.request` method, see:
|
| 162 |
+
https://docs.python-requests.org/en/latest/api/#requests.request.
|
| 163 |
+
For example, you can use `cert=("cert_pem_path", "key_pem_path")`
|
| 164 |
+
to set up client side SSL certificate, and use
|
| 165 |
+
`verify="ca_bundle_path"` to set up the CA certificates for sever
|
| 166 |
+
side SSL certificate verification.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating
|
| 170 |
+
if the request is successful, a mapping for the JSON-decoded response
|
| 171 |
+
data and in the case of an error a boolean indicating if the error
|
| 172 |
+
is retryable.
|
| 173 |
+
"""
|
| 174 |
+
if use_json:
|
| 175 |
+
headers_to_use = {"Content-Type": _JSON_CONTENT_TYPE}
|
| 176 |
+
body = json.dumps(body).encode("utf-8")
|
| 177 |
+
else:
|
| 178 |
+
headers_to_use = {"Content-Type": _URLENCODED_CONTENT_TYPE}
|
| 179 |
+
body = urllib.parse.urlencode(body).encode("utf-8")
|
| 180 |
+
|
| 181 |
+
if access_token:
|
| 182 |
+
headers_to_use["Authorization"] = "Bearer {}".format(access_token)
|
| 183 |
+
|
| 184 |
+
if headers:
|
| 185 |
+
headers_to_use.update(headers)
|
| 186 |
+
|
| 187 |
+
response_data = {}
|
| 188 |
+
retryable_error = False
|
| 189 |
+
|
| 190 |
+
retries = _exponential_backoff.ExponentialBackoff()
|
| 191 |
+
for _ in retries:
|
| 192 |
+
response = request(
|
| 193 |
+
method="POST", url=token_uri, headers=headers_to_use, body=body, **kwargs
|
| 194 |
+
)
|
| 195 |
+
response_body = (
|
| 196 |
+
response.data.decode("utf-8")
|
| 197 |
+
if hasattr(response.data, "decode")
|
| 198 |
+
else response.data
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
try:
|
| 202 |
+
# response_body should be a JSON
|
| 203 |
+
response_data = json.loads(response_body)
|
| 204 |
+
except ValueError:
|
| 205 |
+
response_data = response_body
|
| 206 |
+
|
| 207 |
+
if response.status == http_client.OK:
|
| 208 |
+
return True, response_data, None
|
| 209 |
+
|
| 210 |
+
retryable_error = _can_retry(
|
| 211 |
+
status_code=response.status, response_data=response_data
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if not can_retry or not retryable_error:
|
| 215 |
+
return False, response_data, retryable_error
|
| 216 |
+
|
| 217 |
+
return False, response_data, retryable_error
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _token_endpoint_request(
|
| 221 |
+
request,
|
| 222 |
+
token_uri,
|
| 223 |
+
body,
|
| 224 |
+
access_token=None,
|
| 225 |
+
use_json=False,
|
| 226 |
+
can_retry=True,
|
| 227 |
+
headers=None,
|
| 228 |
+
**kwargs
|
| 229 |
+
):
|
| 230 |
+
"""Makes a request to the OAuth 2.0 authorization server's token endpoint.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
request (google.auth.transport.Request): A callable used to make
|
| 234 |
+
HTTP requests.
|
| 235 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 236 |
+
URI.
|
| 237 |
+
body (Mapping[str, str]): The parameters to send in the request body.
|
| 238 |
+
access_token (Optional(str)): The access token needed to make the request.
|
| 239 |
+
use_json (Optional(bool)): Use urlencoded format or json format for the
|
| 240 |
+
content type. The default value is False.
|
| 241 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 242 |
+
headers (Optional[Mapping[str, str]]): The headers for the request.
|
| 243 |
+
kwargs: Additional arguments passed on to the request method. The
|
| 244 |
+
kwargs will be passed to `requests.request` method, see:
|
| 245 |
+
https://docs.python-requests.org/en/latest/api/#requests.request.
|
| 246 |
+
For example, you can use `cert=("cert_pem_path", "key_pem_path")`
|
| 247 |
+
to set up client side SSL certificate, and use
|
| 248 |
+
`verify="ca_bundle_path"` to set up the CA certificates for sever
|
| 249 |
+
side SSL certificate verification.
|
| 250 |
+
|
| 251 |
+
Returns:
|
| 252 |
+
Mapping[str, str]: The JSON-decoded response data.
|
| 253 |
+
|
| 254 |
+
Raises:
|
| 255 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 256 |
+
an error.
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
response_status_ok, response_data, retryable_error = _token_endpoint_request_no_throw(
|
| 260 |
+
request,
|
| 261 |
+
token_uri,
|
| 262 |
+
body,
|
| 263 |
+
access_token=access_token,
|
| 264 |
+
use_json=use_json,
|
| 265 |
+
can_retry=can_retry,
|
| 266 |
+
headers=headers,
|
| 267 |
+
**kwargs
|
| 268 |
+
)
|
| 269 |
+
if not response_status_ok:
|
| 270 |
+
_handle_error_response(response_data, retryable_error)
|
| 271 |
+
return response_data
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def jwt_grant(request, token_uri, assertion, can_retry=True):
|
| 275 |
+
"""Implements the JWT Profile for OAuth 2.0 Authorization Grants.
|
| 276 |
+
|
| 277 |
+
For more details, see `rfc7523 section 4`_.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
request (google.auth.transport.Request): A callable used to make
|
| 281 |
+
HTTP requests.
|
| 282 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 283 |
+
URI.
|
| 284 |
+
assertion (str): The OAuth 2.0 assertion.
|
| 285 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
|
| 289 |
+
expiration, and additional data returned by the token endpoint.
|
| 290 |
+
|
| 291 |
+
Raises:
|
| 292 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 293 |
+
an error.
|
| 294 |
+
|
| 295 |
+
.. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
|
| 296 |
+
"""
|
| 297 |
+
body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
|
| 298 |
+
|
| 299 |
+
response_data = _token_endpoint_request(
|
| 300 |
+
request,
|
| 301 |
+
token_uri,
|
| 302 |
+
body,
|
| 303 |
+
can_retry=can_retry,
|
| 304 |
+
headers={
|
| 305 |
+
metrics.API_CLIENT_HEADER: metrics.token_request_access_token_sa_assertion()
|
| 306 |
+
},
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
try:
|
| 310 |
+
access_token = response_data["access_token"]
|
| 311 |
+
except KeyError as caught_exc:
|
| 312 |
+
new_exc = exceptions.RefreshError(
|
| 313 |
+
"No access token in response.", response_data, retryable=False
|
| 314 |
+
)
|
| 315 |
+
raise new_exc from caught_exc
|
| 316 |
+
|
| 317 |
+
expiry = _parse_expiry(response_data)
|
| 318 |
+
|
| 319 |
+
return access_token, expiry, response_data
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def call_iam_generate_id_token_endpoint(
|
| 323 |
+
request,
|
| 324 |
+
iam_id_token_endpoint,
|
| 325 |
+
signer_email,
|
| 326 |
+
audience,
|
| 327 |
+
access_token,
|
| 328 |
+
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
|
| 329 |
+
):
|
| 330 |
+
"""Call iam.generateIdToken endpoint to get ID token.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
request (google.auth.transport.Request): A callable used to make
|
| 334 |
+
HTTP requests.
|
| 335 |
+
iam_id_token_endpoint (str): The IAM ID token endpoint to use.
|
| 336 |
+
signer_email (str): The signer email used to form the IAM
|
| 337 |
+
generateIdToken endpoint.
|
| 338 |
+
audience (str): The audience for the ID token.
|
| 339 |
+
access_token (str): The access token used to call the IAM endpoint.
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
Tuple[str, datetime]: The ID token and expiration.
|
| 343 |
+
"""
|
| 344 |
+
body = {"audience": audience, "includeEmail": "true", "useEmailAzp": "true"}
|
| 345 |
+
|
| 346 |
+
response_data = _token_endpoint_request(
|
| 347 |
+
request,
|
| 348 |
+
iam_id_token_endpoint.replace(
|
| 349 |
+
credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain
|
| 350 |
+
).format(signer_email),
|
| 351 |
+
body,
|
| 352 |
+
access_token=access_token,
|
| 353 |
+
use_json=True,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
try:
|
| 357 |
+
id_token = response_data["token"]
|
| 358 |
+
except KeyError as caught_exc:
|
| 359 |
+
new_exc = exceptions.RefreshError(
|
| 360 |
+
"No ID token in response.", response_data, retryable=False
|
| 361 |
+
)
|
| 362 |
+
raise new_exc from caught_exc
|
| 363 |
+
|
| 364 |
+
payload = jwt.decode(id_token, verify=False)
|
| 365 |
+
expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
|
| 366 |
+
|
| 367 |
+
return id_token, expiry
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def id_token_jwt_grant(request, token_uri, assertion, can_retry=True):
|
| 371 |
+
"""Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
|
| 372 |
+
requests an OpenID Connect ID Token instead of an access token.
|
| 373 |
+
|
| 374 |
+
This is a variant on the standard JWT Profile that is currently unique
|
| 375 |
+
to Google. This was added for the benefit of authenticating to services
|
| 376 |
+
that require ID Tokens instead of access tokens or JWT bearer tokens.
|
| 377 |
+
|
| 378 |
+
Args:
|
| 379 |
+
request (google.auth.transport.Request): A callable used to make
|
| 380 |
+
HTTP requests.
|
| 381 |
+
token_uri (str): The OAuth 2.0 authorization server's token endpoint
|
| 382 |
+
URI.
|
| 383 |
+
assertion (str): JWT token signed by a service account. The token's
|
| 384 |
+
payload must include a ``target_audience`` claim.
|
| 385 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
Tuple[str, Optional[datetime], Mapping[str, str]]:
|
| 389 |
+
The (encoded) Open ID Connect ID Token, expiration, and additional
|
| 390 |
+
data returned by the endpoint.
|
| 391 |
+
|
| 392 |
+
Raises:
|
| 393 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 394 |
+
an error.
|
| 395 |
+
"""
|
| 396 |
+
body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
|
| 397 |
+
|
| 398 |
+
response_data = _token_endpoint_request(
|
| 399 |
+
request,
|
| 400 |
+
token_uri,
|
| 401 |
+
body,
|
| 402 |
+
can_retry=can_retry,
|
| 403 |
+
headers={
|
| 404 |
+
metrics.API_CLIENT_HEADER: metrics.token_request_id_token_sa_assertion()
|
| 405 |
+
},
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
try:
|
| 409 |
+
id_token = response_data["id_token"]
|
| 410 |
+
except KeyError as caught_exc:
|
| 411 |
+
new_exc = exceptions.RefreshError(
|
| 412 |
+
"No ID token in response.", response_data, retryable=False
|
| 413 |
+
)
|
| 414 |
+
raise new_exc from caught_exc
|
| 415 |
+
|
| 416 |
+
payload = jwt.decode(id_token, verify=False)
|
| 417 |
+
expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
|
| 418 |
+
|
| 419 |
+
return id_token, expiry, response_data
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _handle_refresh_grant_response(response_data, refresh_token):
|
| 423 |
+
"""Extract tokens from refresh grant response.
|
| 424 |
+
|
| 425 |
+
Args:
|
| 426 |
+
response_data (Mapping[str, str]): Refresh grant response data.
|
| 427 |
+
refresh_token (str): Current refresh token.
|
| 428 |
+
|
| 429 |
+
Returns:
|
| 430 |
+
Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access token,
|
| 431 |
+
refresh token, expiration, and additional data returned by the token
|
| 432 |
+
endpoint. If response_data doesn't have refresh token, then the current
|
| 433 |
+
refresh token will be returned.
|
| 434 |
+
|
| 435 |
+
Raises:
|
| 436 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 437 |
+
an error.
|
| 438 |
+
"""
|
| 439 |
+
try:
|
| 440 |
+
access_token = response_data["access_token"]
|
| 441 |
+
except KeyError as caught_exc:
|
| 442 |
+
new_exc = exceptions.RefreshError(
|
| 443 |
+
"No access token in response.", response_data, retryable=False
|
| 444 |
+
)
|
| 445 |
+
raise new_exc from caught_exc
|
| 446 |
+
|
| 447 |
+
refresh_token = response_data.get("refresh_token", refresh_token)
|
| 448 |
+
expiry = _parse_expiry(response_data)
|
| 449 |
+
|
| 450 |
+
return access_token, refresh_token, expiry, response_data
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def refresh_grant(
|
| 454 |
+
request,
|
| 455 |
+
token_uri,
|
| 456 |
+
refresh_token,
|
| 457 |
+
client_id,
|
| 458 |
+
client_secret,
|
| 459 |
+
scopes=None,
|
| 460 |
+
rapt_token=None,
|
| 461 |
+
can_retry=True,
|
| 462 |
+
):
|
| 463 |
+
"""Implements the OAuth 2.0 refresh token grant.
|
| 464 |
+
|
| 465 |
+
For more details, see `rfc678 section 6`_.
|
| 466 |
+
|
| 467 |
+
Args:
|
| 468 |
+
request (google.auth.transport.Request): A callable used to make
|
| 469 |
+
HTTP requests.
|
| 470 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 471 |
+
URI.
|
| 472 |
+
refresh_token (str): The refresh token to use to get a new access
|
| 473 |
+
token.
|
| 474 |
+
client_id (str): The OAuth 2.0 application's client ID.
|
| 475 |
+
client_secret (str): The Oauth 2.0 appliaction's client secret.
|
| 476 |
+
scopes (Optional(Sequence[str])): Scopes to request. If present, all
|
| 477 |
+
scopes must be authorized for the refresh token. Useful if refresh
|
| 478 |
+
token has a wild card scope (e.g.
|
| 479 |
+
'https://www.googleapis.com/auth/any-api').
|
| 480 |
+
rapt_token (Optional(str)): The reauth Proof Token.
|
| 481 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 482 |
+
|
| 483 |
+
Returns:
|
| 484 |
+
Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access
|
| 485 |
+
token, new or current refresh token, expiration, and additional data
|
| 486 |
+
returned by the token endpoint.
|
| 487 |
+
|
| 488 |
+
Raises:
|
| 489 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 490 |
+
an error.
|
| 491 |
+
|
| 492 |
+
.. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
|
| 493 |
+
"""
|
| 494 |
+
body = {
|
| 495 |
+
"grant_type": _REFRESH_GRANT_TYPE,
|
| 496 |
+
"client_id": client_id,
|
| 497 |
+
"client_secret": client_secret,
|
| 498 |
+
"refresh_token": refresh_token,
|
| 499 |
+
}
|
| 500 |
+
if scopes:
|
| 501 |
+
body["scope"] = " ".join(scopes)
|
| 502 |
+
if rapt_token:
|
| 503 |
+
body["rapt"] = rapt_token
|
| 504 |
+
|
| 505 |
+
response_data = _token_endpoint_request(
|
| 506 |
+
request, token_uri, body, can_retry=can_retry
|
| 507 |
+
)
|
| 508 |
+
return _handle_refresh_grant_response(response_data, refresh_token)
|
lib/python3.10/site-packages/google/oauth2/_client_async.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 |
+
"""OAuth 2.0 async client.
|
| 16 |
+
|
| 17 |
+
This is a client for interacting with an OAuth 2.0 authorization server's
|
| 18 |
+
token endpoint.
|
| 19 |
+
|
| 20 |
+
For more information about the token endpoint, see
|
| 21 |
+
`Section 3.1 of rfc6749`_
|
| 22 |
+
|
| 23 |
+
.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import datetime
|
| 27 |
+
import http.client as http_client
|
| 28 |
+
import json
|
| 29 |
+
import urllib
|
| 30 |
+
|
| 31 |
+
from google.auth import _exponential_backoff
|
| 32 |
+
from google.auth import exceptions
|
| 33 |
+
from google.auth import jwt
|
| 34 |
+
from google.oauth2 import _client as client
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
async def _token_endpoint_request_no_throw(
|
| 38 |
+
request, token_uri, body, access_token=None, use_json=False, can_retry=True
|
| 39 |
+
):
|
| 40 |
+
"""Makes a request to the OAuth 2.0 authorization server's token endpoint.
|
| 41 |
+
This function doesn't throw on response errors.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
request (google.auth.transport.Request): A callable used to make
|
| 45 |
+
HTTP requests.
|
| 46 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 47 |
+
URI.
|
| 48 |
+
body (Mapping[str, str]): The parameters to send in the request body.
|
| 49 |
+
access_token (Optional(str)): The access token needed to make the request.
|
| 50 |
+
use_json (Optional(bool)): Use urlencoded format or json format for the
|
| 51 |
+
content type. The default value is False.
|
| 52 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating
|
| 56 |
+
if the request is successful, a mapping for the JSON-decoded response
|
| 57 |
+
data and in the case of an error a boolean indicating if the error
|
| 58 |
+
is retryable.
|
| 59 |
+
"""
|
| 60 |
+
if use_json:
|
| 61 |
+
headers = {"Content-Type": client._JSON_CONTENT_TYPE}
|
| 62 |
+
body = json.dumps(body).encode("utf-8")
|
| 63 |
+
else:
|
| 64 |
+
headers = {"Content-Type": client._URLENCODED_CONTENT_TYPE}
|
| 65 |
+
body = urllib.parse.urlencode(body).encode("utf-8")
|
| 66 |
+
|
| 67 |
+
if access_token:
|
| 68 |
+
headers["Authorization"] = "Bearer {}".format(access_token)
|
| 69 |
+
|
| 70 |
+
response_data = {}
|
| 71 |
+
retryable_error = False
|
| 72 |
+
|
| 73 |
+
retries = _exponential_backoff.ExponentialBackoff()
|
| 74 |
+
for _ in retries:
|
| 75 |
+
response = await request(
|
| 76 |
+
method="POST", url=token_uri, headers=headers, body=body
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Using data.read() resulted in zlib decompression errors. This may require future investigation.
|
| 80 |
+
response_body1 = await response.content()
|
| 81 |
+
|
| 82 |
+
response_body = (
|
| 83 |
+
response_body1.decode("utf-8")
|
| 84 |
+
if hasattr(response_body1, "decode")
|
| 85 |
+
else response_body1
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
response_data = json.loads(response_body)
|
| 90 |
+
except ValueError:
|
| 91 |
+
response_data = response_body
|
| 92 |
+
|
| 93 |
+
if response.status == http_client.OK:
|
| 94 |
+
return True, response_data, None
|
| 95 |
+
|
| 96 |
+
retryable_error = client._can_retry(
|
| 97 |
+
status_code=response.status, response_data=response_data
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if not can_retry or not retryable_error:
|
| 101 |
+
return False, response_data, retryable_error
|
| 102 |
+
|
| 103 |
+
return False, response_data, retryable_error
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
async def _token_endpoint_request(
|
| 107 |
+
request, token_uri, body, access_token=None, use_json=False, can_retry=True
|
| 108 |
+
):
|
| 109 |
+
"""Makes a request to the OAuth 2.0 authorization server's token endpoint.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
request (google.auth.transport.Request): A callable used to make
|
| 113 |
+
HTTP requests.
|
| 114 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 115 |
+
URI.
|
| 116 |
+
body (Mapping[str, str]): The parameters to send in the request body.
|
| 117 |
+
access_token (Optional(str)): The access token needed to make the request.
|
| 118 |
+
use_json (Optional(bool)): Use urlencoded format or json format for the
|
| 119 |
+
content type. The default value is False.
|
| 120 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
Mapping[str, str]: The JSON-decoded response data.
|
| 124 |
+
|
| 125 |
+
Raises:
|
| 126 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 127 |
+
an error.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
response_status_ok, response_data, retryable_error = await _token_endpoint_request_no_throw(
|
| 131 |
+
request,
|
| 132 |
+
token_uri,
|
| 133 |
+
body,
|
| 134 |
+
access_token=access_token,
|
| 135 |
+
use_json=use_json,
|
| 136 |
+
can_retry=can_retry,
|
| 137 |
+
)
|
| 138 |
+
if not response_status_ok:
|
| 139 |
+
client._handle_error_response(response_data, retryable_error)
|
| 140 |
+
return response_data
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
async def jwt_grant(request, token_uri, assertion, can_retry=True):
|
| 144 |
+
"""Implements the JWT Profile for OAuth 2.0 Authorization Grants.
|
| 145 |
+
|
| 146 |
+
For more details, see `rfc7523 section 4`_.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
request (google.auth.transport.Request): A callable used to make
|
| 150 |
+
HTTP requests.
|
| 151 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 152 |
+
URI.
|
| 153 |
+
assertion (str): The OAuth 2.0 assertion.
|
| 154 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
|
| 158 |
+
expiration, and additional data returned by the token endpoint.
|
| 159 |
+
|
| 160 |
+
Raises:
|
| 161 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 162 |
+
an error.
|
| 163 |
+
|
| 164 |
+
.. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
|
| 165 |
+
"""
|
| 166 |
+
body = {"assertion": assertion, "grant_type": client._JWT_GRANT_TYPE}
|
| 167 |
+
|
| 168 |
+
response_data = await _token_endpoint_request(
|
| 169 |
+
request, token_uri, body, can_retry=can_retry
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
access_token = response_data["access_token"]
|
| 174 |
+
except KeyError as caught_exc:
|
| 175 |
+
new_exc = exceptions.RefreshError(
|
| 176 |
+
"No access token in response.", response_data, retryable=False
|
| 177 |
+
)
|
| 178 |
+
raise new_exc from caught_exc
|
| 179 |
+
|
| 180 |
+
expiry = client._parse_expiry(response_data)
|
| 181 |
+
|
| 182 |
+
return access_token, expiry, response_data
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
async def id_token_jwt_grant(request, token_uri, assertion, can_retry=True):
|
| 186 |
+
"""Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
|
| 187 |
+
requests an OpenID Connect ID Token instead of an access token.
|
| 188 |
+
|
| 189 |
+
This is a variant on the standard JWT Profile that is currently unique
|
| 190 |
+
to Google. This was added for the benefit of authenticating to services
|
| 191 |
+
that require ID Tokens instead of access tokens or JWT bearer tokens.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
request (google.auth.transport.Request): A callable used to make
|
| 195 |
+
HTTP requests.
|
| 196 |
+
token_uri (str): The OAuth 2.0 authorization server's token endpoint
|
| 197 |
+
URI.
|
| 198 |
+
assertion (str): JWT token signed by a service account. The token's
|
| 199 |
+
payload must include a ``target_audience`` claim.
|
| 200 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
Tuple[str, Optional[datetime], Mapping[str, str]]:
|
| 204 |
+
The (encoded) Open ID Connect ID Token, expiration, and additional
|
| 205 |
+
data returned by the endpoint.
|
| 206 |
+
|
| 207 |
+
Raises:
|
| 208 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 209 |
+
an error.
|
| 210 |
+
"""
|
| 211 |
+
body = {"assertion": assertion, "grant_type": client._JWT_GRANT_TYPE}
|
| 212 |
+
|
| 213 |
+
response_data = await _token_endpoint_request(
|
| 214 |
+
request, token_uri, body, can_retry=can_retry
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
id_token = response_data["id_token"]
|
| 219 |
+
except KeyError as caught_exc:
|
| 220 |
+
new_exc = exceptions.RefreshError(
|
| 221 |
+
"No ID token in response.", response_data, retryable=False
|
| 222 |
+
)
|
| 223 |
+
raise new_exc from caught_exc
|
| 224 |
+
|
| 225 |
+
payload = jwt.decode(id_token, verify=False)
|
| 226 |
+
expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
|
| 227 |
+
|
| 228 |
+
return id_token, expiry, response_data
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
async def refresh_grant(
|
| 232 |
+
request,
|
| 233 |
+
token_uri,
|
| 234 |
+
refresh_token,
|
| 235 |
+
client_id,
|
| 236 |
+
client_secret,
|
| 237 |
+
scopes=None,
|
| 238 |
+
rapt_token=None,
|
| 239 |
+
can_retry=True,
|
| 240 |
+
):
|
| 241 |
+
"""Implements the OAuth 2.0 refresh token grant.
|
| 242 |
+
|
| 243 |
+
For more details, see `rfc678 section 6`_.
|
| 244 |
+
|
| 245 |
+
Args:
|
| 246 |
+
request (google.auth.transport.Request): A callable used to make
|
| 247 |
+
HTTP requests.
|
| 248 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 249 |
+
URI.
|
| 250 |
+
refresh_token (str): The refresh token to use to get a new access
|
| 251 |
+
token.
|
| 252 |
+
client_id (str): The OAuth 2.0 application's client ID.
|
| 253 |
+
client_secret (str): The Oauth 2.0 appliaction's client secret.
|
| 254 |
+
scopes (Optional(Sequence[str])): Scopes to request. If present, all
|
| 255 |
+
scopes must be authorized for the refresh token. Useful if refresh
|
| 256 |
+
token has a wild card scope (e.g.
|
| 257 |
+
'https://www.googleapis.com/auth/any-api').
|
| 258 |
+
rapt_token (Optional(str)): The reauth Proof Token.
|
| 259 |
+
can_retry (bool): Enable or disable request retry behavior.
|
| 260 |
+
|
| 261 |
+
Returns:
|
| 262 |
+
Tuple[str, Optional[str], Optional[datetime], Mapping[str, str]]: The
|
| 263 |
+
access token, new or current refresh token, expiration, and additional data
|
| 264 |
+
returned by the token endpoint.
|
| 265 |
+
|
| 266 |
+
Raises:
|
| 267 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 268 |
+
an error.
|
| 269 |
+
|
| 270 |
+
.. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
|
| 271 |
+
"""
|
| 272 |
+
body = {
|
| 273 |
+
"grant_type": client._REFRESH_GRANT_TYPE,
|
| 274 |
+
"client_id": client_id,
|
| 275 |
+
"client_secret": client_secret,
|
| 276 |
+
"refresh_token": refresh_token,
|
| 277 |
+
}
|
| 278 |
+
if scopes:
|
| 279 |
+
body["scope"] = " ".join(scopes)
|
| 280 |
+
if rapt_token:
|
| 281 |
+
body["rapt"] = rapt_token
|
| 282 |
+
|
| 283 |
+
response_data = await _token_endpoint_request(
|
| 284 |
+
request, token_uri, body, can_retry=can_retry
|
| 285 |
+
)
|
| 286 |
+
return client._handle_refresh_grant_response(response_data, refresh_token)
|
lib/python3.10/site-packages/google/oauth2/_id_token_async.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 ID Token helpers.
|
| 16 |
+
|
| 17 |
+
Provides support for verifying `OpenID Connect ID Tokens`_, especially ones
|
| 18 |
+
generated by Google infrastructure.
|
| 19 |
+
|
| 20 |
+
To parse and verify an ID Token issued by Google's OAuth 2.0 authorization
|
| 21 |
+
server use :func:`verify_oauth2_token`. To verify an ID Token issued by
|
| 22 |
+
Firebase, use :func:`verify_firebase_token`.
|
| 23 |
+
|
| 24 |
+
A general purpose ID Token verifier is available as :func:`verify_token`.
|
| 25 |
+
|
| 26 |
+
Example::
|
| 27 |
+
|
| 28 |
+
from google.oauth2 import _id_token_async
|
| 29 |
+
from google.auth.transport import aiohttp_requests
|
| 30 |
+
|
| 31 |
+
request = aiohttp_requests.Request()
|
| 32 |
+
|
| 33 |
+
id_info = await _id_token_async.verify_oauth2_token(
|
| 34 |
+
token, request, 'my-client-id.example.com')
|
| 35 |
+
|
| 36 |
+
if id_info['iss'] != 'https://accounts.google.com':
|
| 37 |
+
raise ValueError('Wrong issuer.')
|
| 38 |
+
|
| 39 |
+
userid = id_info['sub']
|
| 40 |
+
|
| 41 |
+
By default, this will re-fetch certificates for each verification. Because
|
| 42 |
+
Google's public keys are only changed infrequently (on the order of once per
|
| 43 |
+
day), you may wish to take advantage of caching to reduce latency and the
|
| 44 |
+
potential for network errors. This can be accomplished using an external
|
| 45 |
+
library like `CacheControl`_ to create a cache-aware
|
| 46 |
+
:class:`google.auth.transport.Request`::
|
| 47 |
+
|
| 48 |
+
import cachecontrol
|
| 49 |
+
import google.auth.transport.requests
|
| 50 |
+
import requests
|
| 51 |
+
|
| 52 |
+
session = requests.session()
|
| 53 |
+
cached_session = cachecontrol.CacheControl(session)
|
| 54 |
+
request = google.auth.transport.requests.Request(session=cached_session)
|
| 55 |
+
|
| 56 |
+
.. _OpenID Connect ID Token:
|
| 57 |
+
http://openid.net/specs/openid-connect-core-1_0.html#IDToken
|
| 58 |
+
.. _CacheControl: https://cachecontrol.readthedocs.io
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
import http.client as http_client
|
| 62 |
+
import json
|
| 63 |
+
import os
|
| 64 |
+
|
| 65 |
+
from google.auth import environment_vars
|
| 66 |
+
from google.auth import exceptions
|
| 67 |
+
from google.auth import jwt
|
| 68 |
+
from google.auth.transport import requests
|
| 69 |
+
from google.oauth2 import id_token as sync_id_token
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
async def _fetch_certs(request, certs_url):
|
| 73 |
+
"""Fetches certificates.
|
| 74 |
+
|
| 75 |
+
Google-style cerificate endpoints return JSON in the format of
|
| 76 |
+
``{'key id': 'x509 certificate'}``.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
request (google.auth.transport.Request): The object used to make
|
| 80 |
+
HTTP requests. This must be an aiohttp request.
|
| 81 |
+
certs_url (str): The certificate endpoint URL.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
Mapping[str, str]: A mapping of public key ID to x.509 certificate
|
| 85 |
+
data.
|
| 86 |
+
"""
|
| 87 |
+
response = await request(certs_url, method="GET")
|
| 88 |
+
|
| 89 |
+
if response.status != http_client.OK:
|
| 90 |
+
raise exceptions.TransportError(
|
| 91 |
+
"Could not fetch certificates at {}".format(certs_url)
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
data = await response.content()
|
| 95 |
+
|
| 96 |
+
return json.loads(data)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
async def verify_token(
|
| 100 |
+
id_token,
|
| 101 |
+
request,
|
| 102 |
+
audience=None,
|
| 103 |
+
certs_url=sync_id_token._GOOGLE_OAUTH2_CERTS_URL,
|
| 104 |
+
clock_skew_in_seconds=0,
|
| 105 |
+
):
|
| 106 |
+
"""Verifies an ID token and returns the decoded token.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
id_token (Union[str, bytes]): The encoded token.
|
| 110 |
+
request (google.auth.transport.Request): The object used to make
|
| 111 |
+
HTTP requests. This must be an aiohttp request.
|
| 112 |
+
audience (str): The audience that this token is intended for. If None
|
| 113 |
+
then the audience is not verified.
|
| 114 |
+
certs_url (str): The URL that specifies the certificates to use to
|
| 115 |
+
verify the token. This URL should return JSON in the format of
|
| 116 |
+
``{'key id': 'x509 certificate'}``.
|
| 117 |
+
clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
|
| 118 |
+
validation.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
Mapping[str, Any]: The decoded token.
|
| 122 |
+
"""
|
| 123 |
+
certs = await _fetch_certs(request, certs_url)
|
| 124 |
+
|
| 125 |
+
return jwt.decode(
|
| 126 |
+
id_token,
|
| 127 |
+
certs=certs,
|
| 128 |
+
audience=audience,
|
| 129 |
+
clock_skew_in_seconds=clock_skew_in_seconds,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
async def verify_oauth2_token(
|
| 134 |
+
id_token, request, audience=None, clock_skew_in_seconds=0
|
| 135 |
+
):
|
| 136 |
+
"""Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
id_token (Union[str, bytes]): The encoded token.
|
| 140 |
+
request (google.auth.transport.Request): The object used to make
|
| 141 |
+
HTTP requests. This must be an aiohttp request.
|
| 142 |
+
audience (str): The audience that this token is intended for. This is
|
| 143 |
+
typically your application's OAuth 2.0 client ID. If None then the
|
| 144 |
+
audience is not verified.
|
| 145 |
+
clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
|
| 146 |
+
validation.
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
Mapping[str, Any]: The decoded token.
|
| 150 |
+
|
| 151 |
+
Raises:
|
| 152 |
+
exceptions.GoogleAuthError: If the issuer is invalid.
|
| 153 |
+
"""
|
| 154 |
+
idinfo = await verify_token(
|
| 155 |
+
id_token,
|
| 156 |
+
request,
|
| 157 |
+
audience=audience,
|
| 158 |
+
certs_url=sync_id_token._GOOGLE_OAUTH2_CERTS_URL,
|
| 159 |
+
clock_skew_in_seconds=clock_skew_in_seconds,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if idinfo["iss"] not in sync_id_token._GOOGLE_ISSUERS:
|
| 163 |
+
raise exceptions.GoogleAuthError(
|
| 164 |
+
"Wrong issuer. 'iss' should be one of the following: {}".format(
|
| 165 |
+
sync_id_token._GOOGLE_ISSUERS
|
| 166 |
+
)
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
return idinfo
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
async def verify_firebase_token(
|
| 173 |
+
id_token, request, audience=None, clock_skew_in_seconds=0
|
| 174 |
+
):
|
| 175 |
+
"""Verifies an ID Token issued by Firebase Authentication.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
id_token (Union[str, bytes]): The encoded token.
|
| 179 |
+
request (google.auth.transport.Request): The object used to make
|
| 180 |
+
HTTP requests. This must be an aiohttp request.
|
| 181 |
+
audience (str): The audience that this token is intended for. This is
|
| 182 |
+
typically your Firebase application ID. If None then the audience
|
| 183 |
+
is not verified.
|
| 184 |
+
clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
|
| 185 |
+
validation.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
Mapping[str, Any]: The decoded token.
|
| 189 |
+
"""
|
| 190 |
+
return await verify_token(
|
| 191 |
+
id_token,
|
| 192 |
+
request,
|
| 193 |
+
audience=audience,
|
| 194 |
+
certs_url=sync_id_token._GOOGLE_APIS_CERTS_URL,
|
| 195 |
+
clock_skew_in_seconds=clock_skew_in_seconds,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
async def fetch_id_token(request, audience):
|
| 200 |
+
"""Fetch the ID Token from the current environment.
|
| 201 |
+
|
| 202 |
+
This function acquires ID token from the environment in the following order.
|
| 203 |
+
See https://google.aip.dev/auth/4110.
|
| 204 |
+
|
| 205 |
+
1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
|
| 206 |
+
to the path of a valid service account JSON file, then ID token is
|
| 207 |
+
acquired using this service account credentials.
|
| 208 |
+
2. If the application is running in Compute Engine, App Engine or Cloud Run,
|
| 209 |
+
then the ID token are obtained from the metadata server.
|
| 210 |
+
3. If metadata server doesn't exist and no valid service account credentials
|
| 211 |
+
are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will
|
| 212 |
+
be raised.
|
| 213 |
+
|
| 214 |
+
Example::
|
| 215 |
+
|
| 216 |
+
import google.oauth2._id_token_async
|
| 217 |
+
import google.auth.transport.aiohttp_requests
|
| 218 |
+
|
| 219 |
+
request = google.auth.transport.aiohttp_requests.Request()
|
| 220 |
+
target_audience = "https://pubsub.googleapis.com"
|
| 221 |
+
|
| 222 |
+
id_token = await google.oauth2._id_token_async.fetch_id_token(request, target_audience)
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
request (google.auth.transport.aiohttp_requests.Request): A callable used to make
|
| 226 |
+
HTTP requests.
|
| 227 |
+
audience (str): The audience that this ID token is intended for.
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
str: The ID token.
|
| 231 |
+
|
| 232 |
+
Raises:
|
| 233 |
+
~google.auth.exceptions.DefaultCredentialsError:
|
| 234 |
+
If metadata server doesn't exist and no valid service account
|
| 235 |
+
credentials are found.
|
| 236 |
+
"""
|
| 237 |
+
# 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
|
| 238 |
+
# variable.
|
| 239 |
+
credentials_filename = os.environ.get(environment_vars.CREDENTIALS)
|
| 240 |
+
if credentials_filename:
|
| 241 |
+
if not (
|
| 242 |
+
os.path.exists(credentials_filename)
|
| 243 |
+
and os.path.isfile(credentials_filename)
|
| 244 |
+
):
|
| 245 |
+
raise exceptions.DefaultCredentialsError(
|
| 246 |
+
"GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid."
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
with open(credentials_filename, "r") as f:
|
| 251 |
+
from google.oauth2 import _service_account_async as service_account
|
| 252 |
+
|
| 253 |
+
info = json.load(f)
|
| 254 |
+
if info.get("type") == "service_account":
|
| 255 |
+
credentials = service_account.IDTokenCredentials.from_service_account_info(
|
| 256 |
+
info, target_audience=audience
|
| 257 |
+
)
|
| 258 |
+
await credentials.refresh(request)
|
| 259 |
+
return credentials.token
|
| 260 |
+
except ValueError as caught_exc:
|
| 261 |
+
new_exc = exceptions.DefaultCredentialsError(
|
| 262 |
+
"GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.",
|
| 263 |
+
caught_exc,
|
| 264 |
+
)
|
| 265 |
+
raise new_exc from caught_exc
|
| 266 |
+
|
| 267 |
+
# 2. Try to fetch ID token from metada server if it exists. The code works
|
| 268 |
+
# for GAE and Cloud Run metadata server as well.
|
| 269 |
+
try:
|
| 270 |
+
from google.auth import compute_engine
|
| 271 |
+
from google.auth.compute_engine import _metadata
|
| 272 |
+
|
| 273 |
+
request_new = requests.Request()
|
| 274 |
+
if _metadata.ping(request_new):
|
| 275 |
+
credentials = compute_engine.IDTokenCredentials(
|
| 276 |
+
request_new, audience, use_metadata_identity_endpoint=True
|
| 277 |
+
)
|
| 278 |
+
credentials.refresh(request_new)
|
| 279 |
+
return credentials.token
|
| 280 |
+
except (ImportError, exceptions.TransportError):
|
| 281 |
+
pass
|
| 282 |
+
|
| 283 |
+
raise exceptions.DefaultCredentialsError(
|
| 284 |
+
"Neither metadata server or valid service account credentials are found."
|
| 285 |
+
)
|
lib/python3.10/site-packages/google/oauth2/_reauth_async.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 |
+
"""A module that provides functions for handling rapt authentication.
|
| 16 |
+
|
| 17 |
+
Reauth is a process of obtaining additional authentication (such as password,
|
| 18 |
+
security token, etc.) while refreshing OAuth 2.0 credentials for a user.
|
| 19 |
+
|
| 20 |
+
Credentials that use the Reauth flow must have the reauth scope,
|
| 21 |
+
``https://www.googleapis.com/auth/accounts.reauth``.
|
| 22 |
+
|
| 23 |
+
This module provides a high-level function for executing the Reauth process,
|
| 24 |
+
:func:`refresh_grant`, and lower-level helpers for doing the individual
|
| 25 |
+
steps of the reauth process.
|
| 26 |
+
|
| 27 |
+
Those steps are:
|
| 28 |
+
|
| 29 |
+
1. Obtaining a list of challenges from the reauth server.
|
| 30 |
+
2. Running through each challenge and sending the result back to the reauth
|
| 31 |
+
server.
|
| 32 |
+
3. Refreshing the access token using the returned rapt token.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import sys
|
| 36 |
+
|
| 37 |
+
from google.auth import exceptions
|
| 38 |
+
from google.oauth2 import _client
|
| 39 |
+
from google.oauth2 import _client_async
|
| 40 |
+
from google.oauth2 import challenges
|
| 41 |
+
from google.oauth2 import reauth
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
async def _get_challenges(
|
| 45 |
+
request, supported_challenge_types, access_token, requested_scopes=None
|
| 46 |
+
):
|
| 47 |
+
"""Does initial request to reauth API to get the challenges.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
request (google.auth.transport.Request): A callable used to make
|
| 51 |
+
HTTP requests. This must be an aiohttp request.
|
| 52 |
+
supported_challenge_types (Sequence[str]): list of challenge names
|
| 53 |
+
supported by the manager.
|
| 54 |
+
access_token (str): Access token with reauth scopes.
|
| 55 |
+
requested_scopes (Optional(Sequence[str])): Authorized scopes for the credentials.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
dict: The response from the reauth API.
|
| 59 |
+
"""
|
| 60 |
+
body = {"supportedChallengeTypes": supported_challenge_types}
|
| 61 |
+
if requested_scopes:
|
| 62 |
+
body["oauthScopesForDomainPolicyLookup"] = requested_scopes
|
| 63 |
+
|
| 64 |
+
return await _client_async._token_endpoint_request(
|
| 65 |
+
request,
|
| 66 |
+
reauth._REAUTH_API + ":start",
|
| 67 |
+
body,
|
| 68 |
+
access_token=access_token,
|
| 69 |
+
use_json=True,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
async def _send_challenge_result(
|
| 74 |
+
request, session_id, challenge_id, client_input, access_token
|
| 75 |
+
):
|
| 76 |
+
"""Attempt to refresh access token by sending next challenge result.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
request (google.auth.transport.Request): A callable used to make
|
| 80 |
+
HTTP requests. This must be an aiohttp request.
|
| 81 |
+
session_id (str): session id returned by the initial reauth call.
|
| 82 |
+
challenge_id (str): challenge id returned by the initial reauth call.
|
| 83 |
+
client_input: dict with a challenge-specific client input. For example:
|
| 84 |
+
``{'credential': password}`` for password challenge.
|
| 85 |
+
access_token (str): Access token with reauth scopes.
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
dict: The response from the reauth API.
|
| 89 |
+
"""
|
| 90 |
+
body = {
|
| 91 |
+
"sessionId": session_id,
|
| 92 |
+
"challengeId": challenge_id,
|
| 93 |
+
"action": "RESPOND",
|
| 94 |
+
"proposalResponse": client_input,
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
return await _client_async._token_endpoint_request(
|
| 98 |
+
request,
|
| 99 |
+
reauth._REAUTH_API + "/{}:continue".format(session_id),
|
| 100 |
+
body,
|
| 101 |
+
access_token=access_token,
|
| 102 |
+
use_json=True,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
async def _run_next_challenge(msg, request, access_token):
|
| 107 |
+
"""Get the next challenge from msg and run it.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
msg (dict): Reauth API response body (either from the initial request to
|
| 111 |
+
https://reauth.googleapis.com/v2/sessions:start or from sending the
|
| 112 |
+
previous challenge response to
|
| 113 |
+
https://reauth.googleapis.com/v2/sessions/id:continue)
|
| 114 |
+
request (google.auth.transport.Request): A callable used to make
|
| 115 |
+
HTTP requests. This must be an aiohttp request.
|
| 116 |
+
access_token (str): reauth access token
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
dict: The response from the reauth API.
|
| 120 |
+
|
| 121 |
+
Raises:
|
| 122 |
+
google.auth.exceptions.ReauthError: if reauth failed.
|
| 123 |
+
"""
|
| 124 |
+
for challenge in msg["challenges"]:
|
| 125 |
+
if challenge["status"] != "READY":
|
| 126 |
+
# Skip non-activated challenges.
|
| 127 |
+
continue
|
| 128 |
+
c = challenges.AVAILABLE_CHALLENGES.get(challenge["challengeType"], None)
|
| 129 |
+
if not c:
|
| 130 |
+
raise exceptions.ReauthFailError(
|
| 131 |
+
"Unsupported challenge type {0}. Supported types: {1}".format(
|
| 132 |
+
challenge["challengeType"],
|
| 133 |
+
",".join(list(challenges.AVAILABLE_CHALLENGES.keys())),
|
| 134 |
+
)
|
| 135 |
+
)
|
| 136 |
+
if not c.is_locally_eligible:
|
| 137 |
+
raise exceptions.ReauthFailError(
|
| 138 |
+
"Challenge {0} is not locally eligible".format(
|
| 139 |
+
challenge["challengeType"]
|
| 140 |
+
)
|
| 141 |
+
)
|
| 142 |
+
client_input = c.obtain_challenge_input(challenge)
|
| 143 |
+
if not client_input:
|
| 144 |
+
return None
|
| 145 |
+
return await _send_challenge_result(
|
| 146 |
+
request,
|
| 147 |
+
msg["sessionId"],
|
| 148 |
+
challenge["challengeId"],
|
| 149 |
+
client_input,
|
| 150 |
+
access_token,
|
| 151 |
+
)
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
async def _obtain_rapt(request, access_token, requested_scopes):
|
| 156 |
+
"""Given an http request method and reauth access token, get rapt token.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
request (google.auth.transport.Request): A callable used to make
|
| 160 |
+
HTTP requests. This must be an aiohttp request.
|
| 161 |
+
access_token (str): reauth access token
|
| 162 |
+
requested_scopes (Sequence[str]): scopes required by the client application
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
str: The rapt token.
|
| 166 |
+
|
| 167 |
+
Raises:
|
| 168 |
+
google.auth.exceptions.ReauthError: if reauth failed
|
| 169 |
+
"""
|
| 170 |
+
msg = await _get_challenges(
|
| 171 |
+
request,
|
| 172 |
+
list(challenges.AVAILABLE_CHALLENGES.keys()),
|
| 173 |
+
access_token,
|
| 174 |
+
requested_scopes,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if msg["status"] == reauth._AUTHENTICATED:
|
| 178 |
+
return msg["encodedProofOfReauthToken"]
|
| 179 |
+
|
| 180 |
+
for _ in range(0, reauth.RUN_CHALLENGE_RETRY_LIMIT):
|
| 181 |
+
if not (
|
| 182 |
+
msg["status"] == reauth._CHALLENGE_REQUIRED
|
| 183 |
+
or msg["status"] == reauth._CHALLENGE_PENDING
|
| 184 |
+
):
|
| 185 |
+
raise exceptions.ReauthFailError(
|
| 186 |
+
"Reauthentication challenge failed due to API error: {}".format(
|
| 187 |
+
msg["status"]
|
| 188 |
+
)
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if not reauth.is_interactive():
|
| 192 |
+
raise exceptions.ReauthFailError(
|
| 193 |
+
"Reauthentication challenge could not be answered because you are not"
|
| 194 |
+
" in an interactive session."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
msg = await _run_next_challenge(msg, request, access_token)
|
| 198 |
+
|
| 199 |
+
if msg["status"] == reauth._AUTHENTICATED:
|
| 200 |
+
return msg["encodedProofOfReauthToken"]
|
| 201 |
+
|
| 202 |
+
# If we got here it means we didn't get authenticated.
|
| 203 |
+
raise exceptions.ReauthFailError("Failed to obtain rapt token.")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
async def get_rapt_token(
|
| 207 |
+
request, client_id, client_secret, refresh_token, token_uri, scopes=None
|
| 208 |
+
):
|
| 209 |
+
"""Given an http request method and refresh_token, get rapt token.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
request (google.auth.transport.Request): A callable used to make
|
| 213 |
+
HTTP requests. This must be an aiohttp request.
|
| 214 |
+
client_id (str): client id to get access token for reauth scope.
|
| 215 |
+
client_secret (str): client secret for the client_id
|
| 216 |
+
refresh_token (str): refresh token to refresh access token
|
| 217 |
+
token_uri (str): uri to refresh access token
|
| 218 |
+
scopes (Optional(Sequence[str])): scopes required by the client application
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
str: The rapt token.
|
| 222 |
+
Raises:
|
| 223 |
+
google.auth.exceptions.RefreshError: If reauth failed.
|
| 224 |
+
"""
|
| 225 |
+
sys.stderr.write("Reauthentication required.\n")
|
| 226 |
+
|
| 227 |
+
# Get access token for reauth.
|
| 228 |
+
access_token, _, _, _ = await _client_async.refresh_grant(
|
| 229 |
+
request=request,
|
| 230 |
+
client_id=client_id,
|
| 231 |
+
client_secret=client_secret,
|
| 232 |
+
refresh_token=refresh_token,
|
| 233 |
+
token_uri=token_uri,
|
| 234 |
+
scopes=[reauth._REAUTH_SCOPE],
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
# Get rapt token from reauth API.
|
| 238 |
+
rapt_token = await _obtain_rapt(request, access_token, requested_scopes=scopes)
|
| 239 |
+
|
| 240 |
+
return rapt_token
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
async def refresh_grant(
|
| 244 |
+
request,
|
| 245 |
+
token_uri,
|
| 246 |
+
refresh_token,
|
| 247 |
+
client_id,
|
| 248 |
+
client_secret,
|
| 249 |
+
scopes=None,
|
| 250 |
+
rapt_token=None,
|
| 251 |
+
enable_reauth_refresh=False,
|
| 252 |
+
):
|
| 253 |
+
"""Implements the reauthentication flow.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
request (google.auth.transport.Request): A callable used to make
|
| 257 |
+
HTTP requests. This must be an aiohttp request.
|
| 258 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 259 |
+
URI.
|
| 260 |
+
refresh_token (str): The refresh token to use to get a new access
|
| 261 |
+
token.
|
| 262 |
+
client_id (str): The OAuth 2.0 application's client ID.
|
| 263 |
+
client_secret (str): The Oauth 2.0 appliaction's client secret.
|
| 264 |
+
scopes (Optional(Sequence[str])): Scopes to request. If present, all
|
| 265 |
+
scopes must be authorized for the refresh token. Useful if refresh
|
| 266 |
+
token has a wild card scope (e.g.
|
| 267 |
+
'https://www.googleapis.com/auth/any-api').
|
| 268 |
+
rapt_token (Optional(str)): The rapt token for reauth.
|
| 269 |
+
enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
|
| 270 |
+
should be used. The default value is False. This option is for
|
| 271 |
+
gcloud only, other users should use the default value.
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
Tuple[str, Optional[str], Optional[datetime], Mapping[str, str], str]: The
|
| 275 |
+
access token, new refresh token, expiration, the additional data
|
| 276 |
+
returned by the token endpoint, and the rapt token.
|
| 277 |
+
|
| 278 |
+
Raises:
|
| 279 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 280 |
+
an error.
|
| 281 |
+
"""
|
| 282 |
+
body = {
|
| 283 |
+
"grant_type": _client._REFRESH_GRANT_TYPE,
|
| 284 |
+
"client_id": client_id,
|
| 285 |
+
"client_secret": client_secret,
|
| 286 |
+
"refresh_token": refresh_token,
|
| 287 |
+
}
|
| 288 |
+
if scopes:
|
| 289 |
+
body["scope"] = " ".join(scopes)
|
| 290 |
+
if rapt_token:
|
| 291 |
+
body["rapt"] = rapt_token
|
| 292 |
+
|
| 293 |
+
response_status_ok, response_data, retryable_error = await _client_async._token_endpoint_request_no_throw(
|
| 294 |
+
request, token_uri, body
|
| 295 |
+
)
|
| 296 |
+
if (
|
| 297 |
+
not response_status_ok
|
| 298 |
+
and response_data.get("error") == reauth._REAUTH_NEEDED_ERROR
|
| 299 |
+
and (
|
| 300 |
+
response_data.get("error_subtype")
|
| 301 |
+
== reauth._REAUTH_NEEDED_ERROR_INVALID_RAPT
|
| 302 |
+
or response_data.get("error_subtype")
|
| 303 |
+
== reauth._REAUTH_NEEDED_ERROR_RAPT_REQUIRED
|
| 304 |
+
)
|
| 305 |
+
):
|
| 306 |
+
if not enable_reauth_refresh:
|
| 307 |
+
raise exceptions.RefreshError(
|
| 308 |
+
"Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate."
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
rapt_token = await get_rapt_token(
|
| 312 |
+
request, client_id, client_secret, refresh_token, token_uri, scopes=scopes
|
| 313 |
+
)
|
| 314 |
+
body["rapt"] = rapt_token
|
| 315 |
+
(
|
| 316 |
+
response_status_ok,
|
| 317 |
+
response_data,
|
| 318 |
+
retryable_error,
|
| 319 |
+
) = await _client_async._token_endpoint_request_no_throw(
|
| 320 |
+
request, token_uri, body
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
if not response_status_ok:
|
| 324 |
+
_client._handle_error_response(response_data, retryable_error)
|
| 325 |
+
refresh_response = _client._handle_refresh_grant_response(
|
| 326 |
+
response_data, refresh_token
|
| 327 |
+
)
|
| 328 |
+
return refresh_response + (rapt_token,)
|
lib/python3.10/site-packages/google/oauth2/challenges.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 1 |
+
# Copyright 2021 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 |
+
""" Challenges for reauthentication.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import abc
|
| 19 |
+
import base64
|
| 20 |
+
import getpass
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
from google.auth import _helpers
|
| 24 |
+
from google.auth import exceptions
|
| 25 |
+
from google.oauth2 import webauthn_handler_factory
|
| 26 |
+
from google.oauth2.webauthn_types import (
|
| 27 |
+
AuthenticationExtensionsClientInputs,
|
| 28 |
+
GetRequest,
|
| 29 |
+
PublicKeyCredentialDescriptor,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
REAUTH_ORIGIN = "https://accounts.google.com"
|
| 34 |
+
SAML_CHALLENGE_MESSAGE = (
|
| 35 |
+
"Please run `gcloud auth login` to complete reauthentication with SAML."
|
| 36 |
+
)
|
| 37 |
+
WEBAUTHN_TIMEOUT_MS = 120000 # Two minute timeout
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_user_password(text):
|
| 41 |
+
"""Get password from user.
|
| 42 |
+
|
| 43 |
+
Override this function with a different logic if you are using this library
|
| 44 |
+
outside a CLI.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
text (str): message for the password prompt.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
str: password string.
|
| 51 |
+
"""
|
| 52 |
+
return getpass.getpass(text)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ReauthChallenge(metaclass=abc.ABCMeta):
|
| 56 |
+
"""Base class for reauth challenges."""
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
@abc.abstractmethod
|
| 60 |
+
def name(self): # pragma: NO COVER
|
| 61 |
+
"""Returns the name of the challenge."""
|
| 62 |
+
raise NotImplementedError("name property must be implemented")
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
@abc.abstractmethod
|
| 66 |
+
def is_locally_eligible(self): # pragma: NO COVER
|
| 67 |
+
"""Returns true if a challenge is supported locally on this machine."""
|
| 68 |
+
raise NotImplementedError("is_locally_eligible property must be implemented")
|
| 69 |
+
|
| 70 |
+
@abc.abstractmethod
|
| 71 |
+
def obtain_challenge_input(self, metadata): # pragma: NO COVER
|
| 72 |
+
"""Performs logic required to obtain credentials and returns it.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
metadata (Mapping): challenge metadata returned in the 'challenges' field in
|
| 76 |
+
the initial reauth request. Includes the 'challengeType' field
|
| 77 |
+
and other challenge-specific fields.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
response that will be send to the reauth service as the content of
|
| 81 |
+
the 'proposalResponse' field in the request body. Usually a dict
|
| 82 |
+
with the keys specific to the challenge. For example,
|
| 83 |
+
``{'credential': password}`` for password challenge.
|
| 84 |
+
"""
|
| 85 |
+
raise NotImplementedError("obtain_challenge_input method must be implemented")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class PasswordChallenge(ReauthChallenge):
|
| 89 |
+
"""Challenge that asks for user's password."""
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def name(self):
|
| 93 |
+
return "PASSWORD"
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def is_locally_eligible(self):
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
@_helpers.copy_docstring(ReauthChallenge)
|
| 100 |
+
def obtain_challenge_input(self, unused_metadata):
|
| 101 |
+
passwd = get_user_password("Please enter your password:")
|
| 102 |
+
if not passwd:
|
| 103 |
+
passwd = " " # avoid the server crashing in case of no password :D
|
| 104 |
+
return {"credential": passwd}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class SecurityKeyChallenge(ReauthChallenge):
|
| 108 |
+
"""Challenge that asks for user's security key touch."""
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def name(self):
|
| 112 |
+
return "SECURITY_KEY"
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def is_locally_eligible(self):
|
| 116 |
+
return True
|
| 117 |
+
|
| 118 |
+
@_helpers.copy_docstring(ReauthChallenge)
|
| 119 |
+
def obtain_challenge_input(self, metadata):
|
| 120 |
+
# Check if there is an available Webauthn Handler, if not use pyu2f
|
| 121 |
+
try:
|
| 122 |
+
factory = webauthn_handler_factory.WebauthnHandlerFactory()
|
| 123 |
+
webauthn_handler = factory.get_handler()
|
| 124 |
+
if webauthn_handler is not None:
|
| 125 |
+
sys.stderr.write("Please insert and touch your security key\n")
|
| 126 |
+
return self._obtain_challenge_input_webauthn(metadata, webauthn_handler)
|
| 127 |
+
except Exception:
|
| 128 |
+
# Attempt pyu2f if exception in webauthn flow
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
import pyu2f.convenience.authenticator # type: ignore
|
| 133 |
+
import pyu2f.errors # type: ignore
|
| 134 |
+
import pyu2f.model # type: ignore
|
| 135 |
+
except ImportError:
|
| 136 |
+
raise exceptions.ReauthFailError(
|
| 137 |
+
"pyu2f dependency is required to use Security key reauth feature. "
|
| 138 |
+
"It can be installed via `pip install pyu2f` or `pip install google-auth[reauth]`."
|
| 139 |
+
)
|
| 140 |
+
sk = metadata["securityKey"]
|
| 141 |
+
challenges = sk["challenges"]
|
| 142 |
+
# Read both 'applicationId' and 'relyingPartyId', if they are the same, use
|
| 143 |
+
# applicationId, if they are different, use relyingPartyId first and retry
|
| 144 |
+
# with applicationId
|
| 145 |
+
application_id = sk["applicationId"]
|
| 146 |
+
relying_party_id = sk["relyingPartyId"]
|
| 147 |
+
|
| 148 |
+
if application_id != relying_party_id:
|
| 149 |
+
application_parameters = [relying_party_id, application_id]
|
| 150 |
+
else:
|
| 151 |
+
application_parameters = [application_id]
|
| 152 |
+
|
| 153 |
+
challenge_data = []
|
| 154 |
+
for c in challenges:
|
| 155 |
+
kh = c["keyHandle"].encode("ascii")
|
| 156 |
+
key = pyu2f.model.RegisteredKey(bytearray(base64.urlsafe_b64decode(kh)))
|
| 157 |
+
challenge = c["challenge"].encode("ascii")
|
| 158 |
+
challenge = base64.urlsafe_b64decode(challenge)
|
| 159 |
+
challenge_data.append({"key": key, "challenge": challenge})
|
| 160 |
+
|
| 161 |
+
# Track number of tries to suppress error message until all application_parameters
|
| 162 |
+
# are tried.
|
| 163 |
+
tries = 0
|
| 164 |
+
for app_id in application_parameters:
|
| 165 |
+
try:
|
| 166 |
+
tries += 1
|
| 167 |
+
api = pyu2f.convenience.authenticator.CreateCompositeAuthenticator(
|
| 168 |
+
REAUTH_ORIGIN
|
| 169 |
+
)
|
| 170 |
+
response = api.Authenticate(
|
| 171 |
+
app_id, challenge_data, print_callback=sys.stderr.write
|
| 172 |
+
)
|
| 173 |
+
return {"securityKey": response}
|
| 174 |
+
except pyu2f.errors.U2FError as e:
|
| 175 |
+
if e.code == pyu2f.errors.U2FError.DEVICE_INELIGIBLE:
|
| 176 |
+
# Only show error if all app_ids have been tried
|
| 177 |
+
if tries == len(application_parameters):
|
| 178 |
+
sys.stderr.write("Ineligible security key.\n")
|
| 179 |
+
return None
|
| 180 |
+
continue
|
| 181 |
+
if e.code == pyu2f.errors.U2FError.TIMEOUT:
|
| 182 |
+
sys.stderr.write(
|
| 183 |
+
"Timed out while waiting for security key touch.\n"
|
| 184 |
+
)
|
| 185 |
+
else:
|
| 186 |
+
raise e
|
| 187 |
+
except pyu2f.errors.PluginError as e:
|
| 188 |
+
sys.stderr.write("Plugin error: {}.\n".format(e))
|
| 189 |
+
continue
|
| 190 |
+
except pyu2f.errors.NoDeviceFoundError:
|
| 191 |
+
sys.stderr.write("No security key found.\n")
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
def _obtain_challenge_input_webauthn(self, metadata, webauthn_handler):
|
| 195 |
+
sk = metadata.get("securityKey")
|
| 196 |
+
if sk is None:
|
| 197 |
+
raise exceptions.InvalidValue("securityKey is None")
|
| 198 |
+
challenges = sk.get("challenges")
|
| 199 |
+
application_id = sk.get("applicationId")
|
| 200 |
+
relying_party_id = sk.get("relyingPartyId")
|
| 201 |
+
if challenges is None or len(challenges) < 1:
|
| 202 |
+
raise exceptions.InvalidValue("challenges is None or empty")
|
| 203 |
+
if application_id is None:
|
| 204 |
+
raise exceptions.InvalidValue("application_id is None")
|
| 205 |
+
if relying_party_id is None:
|
| 206 |
+
raise exceptions.InvalidValue("relying_party_id is None")
|
| 207 |
+
|
| 208 |
+
allow_credentials = []
|
| 209 |
+
for challenge in challenges:
|
| 210 |
+
kh = challenge.get("keyHandle")
|
| 211 |
+
if kh is None:
|
| 212 |
+
raise exceptions.InvalidValue("keyHandle is None")
|
| 213 |
+
key_handle = self._unpadded_urlsafe_b64recode(kh)
|
| 214 |
+
allow_credentials.append(PublicKeyCredentialDescriptor(id=key_handle))
|
| 215 |
+
|
| 216 |
+
extension = AuthenticationExtensionsClientInputs(appid=application_id)
|
| 217 |
+
|
| 218 |
+
challenge = challenges[0].get("challenge")
|
| 219 |
+
if challenge is None:
|
| 220 |
+
raise exceptions.InvalidValue("challenge is None")
|
| 221 |
+
|
| 222 |
+
get_request = GetRequest(
|
| 223 |
+
origin=REAUTH_ORIGIN,
|
| 224 |
+
rpid=relying_party_id,
|
| 225 |
+
challenge=self._unpadded_urlsafe_b64recode(challenge),
|
| 226 |
+
timeout_ms=WEBAUTHN_TIMEOUT_MS,
|
| 227 |
+
allow_credentials=allow_credentials,
|
| 228 |
+
user_verification="required",
|
| 229 |
+
extensions=extension,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
get_response = webauthn_handler.get(get_request)
|
| 234 |
+
except Exception as e:
|
| 235 |
+
sys.stderr.write("Webauthn Error: {}.\n".format(e))
|
| 236 |
+
raise e
|
| 237 |
+
|
| 238 |
+
response = {
|
| 239 |
+
"clientData": get_response.response.client_data_json,
|
| 240 |
+
"authenticatorData": get_response.response.authenticator_data,
|
| 241 |
+
"signatureData": get_response.response.signature,
|
| 242 |
+
"applicationId": application_id,
|
| 243 |
+
"keyHandle": get_response.id,
|
| 244 |
+
"securityKeyReplyType": 2,
|
| 245 |
+
}
|
| 246 |
+
return {"securityKey": response}
|
| 247 |
+
|
| 248 |
+
def _unpadded_urlsafe_b64recode(self, s):
|
| 249 |
+
"""Converts standard b64 encoded string to url safe b64 encoded string
|
| 250 |
+
with no padding."""
|
| 251 |
+
b = base64.urlsafe_b64decode(s)
|
| 252 |
+
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class SamlChallenge(ReauthChallenge):
|
| 256 |
+
"""Challenge that asks the users to browse to their ID Providers.
|
| 257 |
+
|
| 258 |
+
Currently SAML challenge is not supported. When obtaining the challenge
|
| 259 |
+
input, exception will be raised to instruct the users to run
|
| 260 |
+
`gcloud auth login` for reauthentication.
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
@property
|
| 264 |
+
def name(self):
|
| 265 |
+
return "SAML"
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def is_locally_eligible(self):
|
| 269 |
+
return True
|
| 270 |
+
|
| 271 |
+
def obtain_challenge_input(self, metadata):
|
| 272 |
+
# Magic Arch has not fully supported returning a proper dedirect URL
|
| 273 |
+
# for programmatic SAML users today. So we error our here and request
|
| 274 |
+
# users to use gcloud to complete a login.
|
| 275 |
+
raise exceptions.ReauthSamlChallengeFailError(SAML_CHALLENGE_MESSAGE)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
AVAILABLE_CHALLENGES = {
|
| 279 |
+
challenge.name: challenge
|
| 280 |
+
for challenge in [SecurityKeyChallenge(), PasswordChallenge(), SamlChallenge()]
|
| 281 |
+
}
|
lib/python3.10/site-packages/google/oauth2/credentials.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""OAuth 2.0 Credentials.
|
| 16 |
+
|
| 17 |
+
This module provides credentials based on OAuth 2.0 access and refresh tokens.
|
| 18 |
+
These credentials usually access resources on behalf of a user (resource
|
| 19 |
+
owner).
|
| 20 |
+
|
| 21 |
+
Specifically, this is intended to use access tokens acquired using the
|
| 22 |
+
`Authorization Code grant`_ and can refresh those tokens using a
|
| 23 |
+
optional `refresh token`_.
|
| 24 |
+
|
| 25 |
+
Obtaining the initial access and refresh token is outside of the scope of this
|
| 26 |
+
module. Consult `rfc6749 section 4.1`_ for complete details on the
|
| 27 |
+
Authorization Code grant flow.
|
| 28 |
+
|
| 29 |
+
.. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1
|
| 30 |
+
.. _refresh token: https://tools.ietf.org/html/rfc6749#section-6
|
| 31 |
+
.. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
from datetime import datetime
|
| 35 |
+
import io
|
| 36 |
+
import json
|
| 37 |
+
import logging
|
| 38 |
+
import warnings
|
| 39 |
+
|
| 40 |
+
from google.auth import _cloud_sdk
|
| 41 |
+
from google.auth import _helpers
|
| 42 |
+
from google.auth import credentials
|
| 43 |
+
from google.auth import exceptions
|
| 44 |
+
from google.auth import metrics
|
| 45 |
+
from google.oauth2 import reauth
|
| 46 |
+
|
| 47 |
+
_LOGGER = logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# The Google OAuth 2.0 token endpoint. Used for authorized user credentials.
|
| 51 |
+
_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
|
| 52 |
+
|
| 53 |
+
# The Google OAuth 2.0 token info endpoint. Used for getting token info JSON from access tokens.
|
| 54 |
+
_GOOGLE_OAUTH2_TOKEN_INFO_ENDPOINT = "https://oauth2.googleapis.com/tokeninfo"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class Credentials(credentials.ReadOnlyScoped, credentials.CredentialsWithQuotaProject):
|
| 58 |
+
"""Credentials using OAuth 2.0 access and refresh tokens.
|
| 59 |
+
|
| 60 |
+
The credentials are considered immutable except the tokens and the token
|
| 61 |
+
expiry, which are updated after refresh. If you want to modify the quota
|
| 62 |
+
project, use :meth:`with_quota_project` or ::
|
| 63 |
+
|
| 64 |
+
credentials = credentials.with_quota_project('myproject-123')
|
| 65 |
+
|
| 66 |
+
Reauth is disabled by default. To enable reauth, set the
|
| 67 |
+
`enable_reauth_refresh` parameter to True in the constructor. Note that
|
| 68 |
+
reauth feature is intended for gcloud to use only.
|
| 69 |
+
If reauth is enabled, `pyu2f` dependency has to be installed in order to use security
|
| 70 |
+
key reauth feature. Dependency can be installed via `pip install pyu2f` or `pip install
|
| 71 |
+
google-auth[reauth]`.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
token,
|
| 77 |
+
refresh_token=None,
|
| 78 |
+
id_token=None,
|
| 79 |
+
token_uri=None,
|
| 80 |
+
client_id=None,
|
| 81 |
+
client_secret=None,
|
| 82 |
+
scopes=None,
|
| 83 |
+
default_scopes=None,
|
| 84 |
+
quota_project_id=None,
|
| 85 |
+
expiry=None,
|
| 86 |
+
rapt_token=None,
|
| 87 |
+
refresh_handler=None,
|
| 88 |
+
enable_reauth_refresh=False,
|
| 89 |
+
granted_scopes=None,
|
| 90 |
+
trust_boundary=None,
|
| 91 |
+
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
|
| 92 |
+
account=None,
|
| 93 |
+
):
|
| 94 |
+
"""
|
| 95 |
+
Args:
|
| 96 |
+
token (Optional(str)): The OAuth 2.0 access token. Can be None
|
| 97 |
+
if refresh information is provided.
|
| 98 |
+
refresh_token (str): The OAuth 2.0 refresh token. If specified,
|
| 99 |
+
credentials can be refreshed.
|
| 100 |
+
id_token (str): The Open ID Connect ID Token.
|
| 101 |
+
token_uri (str): The OAuth 2.0 authorization server's token
|
| 102 |
+
endpoint URI. Must be specified for refresh, can be left as
|
| 103 |
+
None if the token can not be refreshed.
|
| 104 |
+
client_id (str): The OAuth 2.0 client ID. Must be specified for
|
| 105 |
+
refresh, can be left as None if the token can not be refreshed.
|
| 106 |
+
client_secret(str): The OAuth 2.0 client secret. Must be specified
|
| 107 |
+
for refresh, can be left as None if the token can not be
|
| 108 |
+
refreshed.
|
| 109 |
+
scopes (Sequence[str]): The scopes used to obtain authorization.
|
| 110 |
+
This parameter is used by :meth:`has_scopes`. OAuth 2.0
|
| 111 |
+
credentials can not request additional scopes after
|
| 112 |
+
authorization. The scopes must be derivable from the refresh
|
| 113 |
+
token if refresh information is provided (e.g. The refresh
|
| 114 |
+
token scopes are a superset of this or contain a wild card
|
| 115 |
+
scope like 'https://www.googleapis.com/auth/any-api').
|
| 116 |
+
default_scopes (Sequence[str]): Default scopes passed by a
|
| 117 |
+
Google client library. Use 'scopes' for user-defined scopes.
|
| 118 |
+
quota_project_id (Optional[str]): The project ID used for quota and billing.
|
| 119 |
+
This project may be different from the project used to
|
| 120 |
+
create the credentials.
|
| 121 |
+
rapt_token (Optional[str]): The reauth Proof Token.
|
| 122 |
+
refresh_handler (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]):
|
| 123 |
+
A callable which takes in the HTTP request callable and the list of
|
| 124 |
+
OAuth scopes and when called returns an access token string for the
|
| 125 |
+
requested scopes and its expiry datetime. This is useful when no
|
| 126 |
+
refresh tokens are provided and tokens are obtained by calling
|
| 127 |
+
some external process on demand. It is particularly useful for
|
| 128 |
+
retrieving downscoped tokens from a token broker.
|
| 129 |
+
enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
|
| 130 |
+
should be used. This flag is for gcloud to use only.
|
| 131 |
+
granted_scopes (Optional[Sequence[str]]): The scopes that were consented/granted by the user.
|
| 132 |
+
This could be different from the requested scopes and it could be empty if granted
|
| 133 |
+
and requested scopes were same.
|
| 134 |
+
trust_boundary (str): String representation of trust boundary meta.
|
| 135 |
+
universe_domain (Optional[str]): The universe domain. The default
|
| 136 |
+
universe domain is googleapis.com.
|
| 137 |
+
account (Optional[str]): The account associated with the credential.
|
| 138 |
+
"""
|
| 139 |
+
super(Credentials, self).__init__()
|
| 140 |
+
self.token = token
|
| 141 |
+
self.expiry = expiry
|
| 142 |
+
self._refresh_token = refresh_token
|
| 143 |
+
self._id_token = id_token
|
| 144 |
+
self._scopes = scopes
|
| 145 |
+
self._default_scopes = default_scopes
|
| 146 |
+
self._granted_scopes = granted_scopes
|
| 147 |
+
self._token_uri = token_uri
|
| 148 |
+
self._client_id = client_id
|
| 149 |
+
self._client_secret = client_secret
|
| 150 |
+
self._quota_project_id = quota_project_id
|
| 151 |
+
self._rapt_token = rapt_token
|
| 152 |
+
self.refresh_handler = refresh_handler
|
| 153 |
+
self._enable_reauth_refresh = enable_reauth_refresh
|
| 154 |
+
self._trust_boundary = trust_boundary
|
| 155 |
+
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 156 |
+
self._account = account or ""
|
| 157 |
+
self._cred_file_path = None
|
| 158 |
+
|
| 159 |
+
def __getstate__(self):
|
| 160 |
+
"""A __getstate__ method must exist for the __setstate__ to be called
|
| 161 |
+
This is identical to the default implementation.
|
| 162 |
+
See https://docs.python.org/3.7/library/pickle.html#object.__setstate__
|
| 163 |
+
"""
|
| 164 |
+
state_dict = self.__dict__.copy()
|
| 165 |
+
# Remove _refresh_handler function as there are limitations pickling and
|
| 166 |
+
# unpickling certain callables (lambda, functools.partial instances)
|
| 167 |
+
# because they need to be importable.
|
| 168 |
+
# Instead, the refresh_handler setter should be used to repopulate this.
|
| 169 |
+
if "_refresh_handler" in state_dict:
|
| 170 |
+
del state_dict["_refresh_handler"]
|
| 171 |
+
|
| 172 |
+
if "_refresh_worker" in state_dict:
|
| 173 |
+
del state_dict["_refresh_worker"]
|
| 174 |
+
return state_dict
|
| 175 |
+
|
| 176 |
+
def __setstate__(self, d):
|
| 177 |
+
"""Credentials pickled with older versions of the class do not have
|
| 178 |
+
all the attributes."""
|
| 179 |
+
self.token = d.get("token")
|
| 180 |
+
self.expiry = d.get("expiry")
|
| 181 |
+
self._refresh_token = d.get("_refresh_token")
|
| 182 |
+
self._id_token = d.get("_id_token")
|
| 183 |
+
self._scopes = d.get("_scopes")
|
| 184 |
+
self._default_scopes = d.get("_default_scopes")
|
| 185 |
+
self._granted_scopes = d.get("_granted_scopes")
|
| 186 |
+
self._token_uri = d.get("_token_uri")
|
| 187 |
+
self._client_id = d.get("_client_id")
|
| 188 |
+
self._client_secret = d.get("_client_secret")
|
| 189 |
+
self._quota_project_id = d.get("_quota_project_id")
|
| 190 |
+
self._rapt_token = d.get("_rapt_token")
|
| 191 |
+
self._enable_reauth_refresh = d.get("_enable_reauth_refresh")
|
| 192 |
+
self._trust_boundary = d.get("_trust_boundary")
|
| 193 |
+
self._universe_domain = (
|
| 194 |
+
d.get("_universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 195 |
+
)
|
| 196 |
+
self._cred_file_path = d.get("_cred_file_path")
|
| 197 |
+
# The refresh_handler setter should be used to repopulate this.
|
| 198 |
+
self._refresh_handler = None
|
| 199 |
+
self._refresh_worker = None
|
| 200 |
+
self._use_non_blocking_refresh = d.get("_use_non_blocking_refresh", False)
|
| 201 |
+
self._account = d.get("_account", "")
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def refresh_token(self):
|
| 205 |
+
"""Optional[str]: The OAuth 2.0 refresh token."""
|
| 206 |
+
return self._refresh_token
|
| 207 |
+
|
| 208 |
+
@property
|
| 209 |
+
def scopes(self):
|
| 210 |
+
"""Optional[str]: The OAuth 2.0 permission scopes."""
|
| 211 |
+
return self._scopes
|
| 212 |
+
|
| 213 |
+
@property
|
| 214 |
+
def granted_scopes(self):
|
| 215 |
+
"""Optional[Sequence[str]]: The OAuth 2.0 permission scopes that were granted by the user."""
|
| 216 |
+
return self._granted_scopes
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def token_uri(self):
|
| 220 |
+
"""Optional[str]: The OAuth 2.0 authorization server's token endpoint
|
| 221 |
+
URI."""
|
| 222 |
+
return self._token_uri
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def id_token(self):
|
| 226 |
+
"""Optional[str]: The Open ID Connect ID Token.
|
| 227 |
+
|
| 228 |
+
Depending on the authorization server and the scopes requested, this
|
| 229 |
+
may be populated when credentials are obtained and updated when
|
| 230 |
+
:meth:`refresh` is called. This token is a JWT. It can be verified
|
| 231 |
+
and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`.
|
| 232 |
+
"""
|
| 233 |
+
return self._id_token
|
| 234 |
+
|
| 235 |
+
@property
|
| 236 |
+
def client_id(self):
|
| 237 |
+
"""Optional[str]: The OAuth 2.0 client ID."""
|
| 238 |
+
return self._client_id
|
| 239 |
+
|
| 240 |
+
@property
|
| 241 |
+
def client_secret(self):
|
| 242 |
+
"""Optional[str]: The OAuth 2.0 client secret."""
|
| 243 |
+
return self._client_secret
|
| 244 |
+
|
| 245 |
+
@property
|
| 246 |
+
def requires_scopes(self):
|
| 247 |
+
"""False: OAuth 2.0 credentials have their scopes set when
|
| 248 |
+
the initial token is requested and can not be changed."""
|
| 249 |
+
return False
|
| 250 |
+
|
| 251 |
+
@property
|
| 252 |
+
def rapt_token(self):
|
| 253 |
+
"""Optional[str]: The reauth Proof Token."""
|
| 254 |
+
return self._rapt_token
|
| 255 |
+
|
| 256 |
+
@property
|
| 257 |
+
def refresh_handler(self):
|
| 258 |
+
"""Returns the refresh handler if available.
|
| 259 |
+
|
| 260 |
+
Returns:
|
| 261 |
+
Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]:
|
| 262 |
+
The current refresh handler.
|
| 263 |
+
"""
|
| 264 |
+
return self._refresh_handler
|
| 265 |
+
|
| 266 |
+
@refresh_handler.setter
|
| 267 |
+
def refresh_handler(self, value):
|
| 268 |
+
"""Updates the current refresh handler.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
value (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]):
|
| 272 |
+
The updated value of the refresh handler.
|
| 273 |
+
|
| 274 |
+
Raises:
|
| 275 |
+
TypeError: If the value is not a callable or None.
|
| 276 |
+
"""
|
| 277 |
+
if not callable(value) and value is not None:
|
| 278 |
+
raise TypeError("The provided refresh_handler is not a callable or None.")
|
| 279 |
+
self._refresh_handler = value
|
| 280 |
+
|
| 281 |
+
@property
|
| 282 |
+
def account(self):
|
| 283 |
+
"""str: The user account associated with the credential. If the account is unknown an empty string is returned."""
|
| 284 |
+
return self._account
|
| 285 |
+
|
| 286 |
+
def _make_copy(self):
|
| 287 |
+
cred = self.__class__(
|
| 288 |
+
self.token,
|
| 289 |
+
refresh_token=self.refresh_token,
|
| 290 |
+
id_token=self.id_token,
|
| 291 |
+
token_uri=self.token_uri,
|
| 292 |
+
client_id=self.client_id,
|
| 293 |
+
client_secret=self.client_secret,
|
| 294 |
+
scopes=self.scopes,
|
| 295 |
+
default_scopes=self.default_scopes,
|
| 296 |
+
granted_scopes=self.granted_scopes,
|
| 297 |
+
quota_project_id=self.quota_project_id,
|
| 298 |
+
rapt_token=self.rapt_token,
|
| 299 |
+
enable_reauth_refresh=self._enable_reauth_refresh,
|
| 300 |
+
trust_boundary=self._trust_boundary,
|
| 301 |
+
universe_domain=self._universe_domain,
|
| 302 |
+
account=self._account,
|
| 303 |
+
)
|
| 304 |
+
cred._cred_file_path = self._cred_file_path
|
| 305 |
+
return cred
|
| 306 |
+
|
| 307 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 308 |
+
def get_cred_info(self):
|
| 309 |
+
if self._cred_file_path:
|
| 310 |
+
cred_info = {
|
| 311 |
+
"credential_source": self._cred_file_path,
|
| 312 |
+
"credential_type": "user credentials",
|
| 313 |
+
}
|
| 314 |
+
if self.account:
|
| 315 |
+
cred_info["principal"] = self.account
|
| 316 |
+
return cred_info
|
| 317 |
+
return None
|
| 318 |
+
|
| 319 |
+
@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
|
| 320 |
+
def with_quota_project(self, quota_project_id):
|
| 321 |
+
cred = self._make_copy()
|
| 322 |
+
cred._quota_project_id = quota_project_id
|
| 323 |
+
return cred
|
| 324 |
+
|
| 325 |
+
@_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
|
| 326 |
+
def with_token_uri(self, token_uri):
|
| 327 |
+
cred = self._make_copy()
|
| 328 |
+
cred._token_uri = token_uri
|
| 329 |
+
return cred
|
| 330 |
+
|
| 331 |
+
def with_account(self, account):
|
| 332 |
+
"""Returns a copy of these credentials with a modified account.
|
| 333 |
+
|
| 334 |
+
Args:
|
| 335 |
+
account (str): The account to set
|
| 336 |
+
|
| 337 |
+
Returns:
|
| 338 |
+
google.oauth2.credentials.Credentials: A new credentials instance.
|
| 339 |
+
"""
|
| 340 |
+
cred = self._make_copy()
|
| 341 |
+
cred._account = account
|
| 342 |
+
return cred
|
| 343 |
+
|
| 344 |
+
@_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
|
| 345 |
+
def with_universe_domain(self, universe_domain):
|
| 346 |
+
cred = self._make_copy()
|
| 347 |
+
cred._universe_domain = universe_domain
|
| 348 |
+
return cred
|
| 349 |
+
|
| 350 |
+
def _metric_header_for_usage(self):
|
| 351 |
+
return metrics.CRED_TYPE_USER
|
| 352 |
+
|
| 353 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 354 |
+
def refresh(self, request):
|
| 355 |
+
if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
|
| 356 |
+
raise exceptions.RefreshError(
|
| 357 |
+
"User credential refresh is only supported in the default "
|
| 358 |
+
"googleapis.com universe domain, but the current universe "
|
| 359 |
+
"domain is {}. If you created the credential with an access "
|
| 360 |
+
"token, it's likely that the provided token is expired now, "
|
| 361 |
+
"please update your code with a valid token.".format(
|
| 362 |
+
self._universe_domain
|
| 363 |
+
)
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
scopes = self._scopes if self._scopes is not None else self._default_scopes
|
| 367 |
+
# Use refresh handler if available and no refresh token is
|
| 368 |
+
# available. This is useful in general when tokens are obtained by calling
|
| 369 |
+
# some external process on demand. It is particularly useful for retrieving
|
| 370 |
+
# downscoped tokens from a token broker.
|
| 371 |
+
if self._refresh_token is None and self.refresh_handler:
|
| 372 |
+
token, expiry = self.refresh_handler(request, scopes=scopes)
|
| 373 |
+
# Validate returned data.
|
| 374 |
+
if not isinstance(token, str):
|
| 375 |
+
raise exceptions.RefreshError(
|
| 376 |
+
"The refresh_handler returned token is not a string."
|
| 377 |
+
)
|
| 378 |
+
if not isinstance(expiry, datetime):
|
| 379 |
+
raise exceptions.RefreshError(
|
| 380 |
+
"The refresh_handler returned expiry is not a datetime object."
|
| 381 |
+
)
|
| 382 |
+
if _helpers.utcnow() >= expiry - _helpers.REFRESH_THRESHOLD:
|
| 383 |
+
raise exceptions.RefreshError(
|
| 384 |
+
"The credentials returned by the refresh_handler are "
|
| 385 |
+
"already expired."
|
| 386 |
+
)
|
| 387 |
+
self.token = token
|
| 388 |
+
self.expiry = expiry
|
| 389 |
+
return
|
| 390 |
+
|
| 391 |
+
if (
|
| 392 |
+
self._refresh_token is None
|
| 393 |
+
or self._token_uri is None
|
| 394 |
+
or self._client_id is None
|
| 395 |
+
or self._client_secret is None
|
| 396 |
+
):
|
| 397 |
+
raise exceptions.RefreshError(
|
| 398 |
+
"The credentials do not contain the necessary fields need to "
|
| 399 |
+
"refresh the access token. You must specify refresh_token, "
|
| 400 |
+
"token_uri, client_id, and client_secret."
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
(
|
| 404 |
+
access_token,
|
| 405 |
+
refresh_token,
|
| 406 |
+
expiry,
|
| 407 |
+
grant_response,
|
| 408 |
+
rapt_token,
|
| 409 |
+
) = reauth.refresh_grant(
|
| 410 |
+
request,
|
| 411 |
+
self._token_uri,
|
| 412 |
+
self._refresh_token,
|
| 413 |
+
self._client_id,
|
| 414 |
+
self._client_secret,
|
| 415 |
+
scopes=scopes,
|
| 416 |
+
rapt_token=self._rapt_token,
|
| 417 |
+
enable_reauth_refresh=self._enable_reauth_refresh,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
self.token = access_token
|
| 421 |
+
self.expiry = expiry
|
| 422 |
+
self._refresh_token = refresh_token
|
| 423 |
+
self._id_token = grant_response.get("id_token")
|
| 424 |
+
self._rapt_token = rapt_token
|
| 425 |
+
|
| 426 |
+
if scopes and "scope" in grant_response:
|
| 427 |
+
requested_scopes = frozenset(scopes)
|
| 428 |
+
self._granted_scopes = grant_response["scope"].split()
|
| 429 |
+
granted_scopes = frozenset(self._granted_scopes)
|
| 430 |
+
scopes_requested_but_not_granted = requested_scopes - granted_scopes
|
| 431 |
+
if scopes_requested_but_not_granted:
|
| 432 |
+
# User might be presented with unbundled scopes at the time of
|
| 433 |
+
# consent. So it is a valid scenario to not have all the requested
|
| 434 |
+
# scopes as part of granted scopes but log a warning in case the
|
| 435 |
+
# developer wants to debug the scenario.
|
| 436 |
+
_LOGGER.warning(
|
| 437 |
+
"Not all requested scopes were granted by the "
|
| 438 |
+
"authorization server, missing scopes {}.".format(
|
| 439 |
+
", ".join(scopes_requested_but_not_granted)
|
| 440 |
+
)
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
@classmethod
|
| 444 |
+
def from_authorized_user_info(cls, info, scopes=None):
|
| 445 |
+
"""Creates a Credentials instance from parsed authorized user info.
|
| 446 |
+
|
| 447 |
+
Args:
|
| 448 |
+
info (Mapping[str, str]): The authorized user info in Google
|
| 449 |
+
format.
|
| 450 |
+
scopes (Sequence[str]): Optional list of scopes to include in the
|
| 451 |
+
credentials.
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
google.oauth2.credentials.Credentials: The constructed
|
| 455 |
+
credentials.
|
| 456 |
+
|
| 457 |
+
Raises:
|
| 458 |
+
ValueError: If the info is not in the expected format.
|
| 459 |
+
"""
|
| 460 |
+
keys_needed = set(("refresh_token", "client_id", "client_secret"))
|
| 461 |
+
missing = keys_needed.difference(info.keys())
|
| 462 |
+
|
| 463 |
+
if missing:
|
| 464 |
+
raise ValueError(
|
| 465 |
+
"Authorized user info was not in the expected format, missing "
|
| 466 |
+
"fields {}.".format(", ".join(missing))
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
# access token expiry (datetime obj); auto-expire if not saved
|
| 470 |
+
expiry = info.get("expiry")
|
| 471 |
+
if expiry:
|
| 472 |
+
expiry = datetime.strptime(
|
| 473 |
+
expiry.rstrip("Z").split(".")[0], "%Y-%m-%dT%H:%M:%S"
|
| 474 |
+
)
|
| 475 |
+
else:
|
| 476 |
+
expiry = _helpers.utcnow() - _helpers.REFRESH_THRESHOLD
|
| 477 |
+
|
| 478 |
+
# process scopes, which needs to be a seq
|
| 479 |
+
if scopes is None and "scopes" in info:
|
| 480 |
+
scopes = info.get("scopes")
|
| 481 |
+
if isinstance(scopes, str):
|
| 482 |
+
scopes = scopes.split(" ")
|
| 483 |
+
|
| 484 |
+
return cls(
|
| 485 |
+
token=info.get("token"),
|
| 486 |
+
refresh_token=info.get("refresh_token"),
|
| 487 |
+
token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, # always overrides
|
| 488 |
+
scopes=scopes,
|
| 489 |
+
client_id=info.get("client_id"),
|
| 490 |
+
client_secret=info.get("client_secret"),
|
| 491 |
+
quota_project_id=info.get("quota_project_id"), # may not exist
|
| 492 |
+
expiry=expiry,
|
| 493 |
+
rapt_token=info.get("rapt_token"), # may not exist
|
| 494 |
+
trust_boundary=info.get("trust_boundary"), # may not exist
|
| 495 |
+
universe_domain=info.get("universe_domain"), # may not exist
|
| 496 |
+
account=info.get("account", ""), # may not exist
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
@classmethod
|
| 500 |
+
def from_authorized_user_file(cls, filename, scopes=None):
|
| 501 |
+
"""Creates a Credentials instance from an authorized user json file.
|
| 502 |
+
|
| 503 |
+
Args:
|
| 504 |
+
filename (str): The path to the authorized user json file.
|
| 505 |
+
scopes (Sequence[str]): Optional list of scopes to include in the
|
| 506 |
+
credentials.
|
| 507 |
+
|
| 508 |
+
Returns:
|
| 509 |
+
google.oauth2.credentials.Credentials: The constructed
|
| 510 |
+
credentials.
|
| 511 |
+
|
| 512 |
+
Raises:
|
| 513 |
+
ValueError: If the file is not in the expected format.
|
| 514 |
+
"""
|
| 515 |
+
with io.open(filename, "r", encoding="utf-8") as json_file:
|
| 516 |
+
data = json.load(json_file)
|
| 517 |
+
return cls.from_authorized_user_info(data, scopes)
|
| 518 |
+
|
| 519 |
+
def to_json(self, strip=None):
|
| 520 |
+
"""Utility function that creates a JSON representation of a Credentials
|
| 521 |
+
object.
|
| 522 |
+
|
| 523 |
+
Args:
|
| 524 |
+
strip (Sequence[str]): Optional list of members to exclude from the
|
| 525 |
+
generated JSON.
|
| 526 |
+
|
| 527 |
+
Returns:
|
| 528 |
+
str: A JSON representation of this instance. When converted into
|
| 529 |
+
a dictionary, it can be passed to from_authorized_user_info()
|
| 530 |
+
to create a new credential instance.
|
| 531 |
+
"""
|
| 532 |
+
prep = {
|
| 533 |
+
"token": self.token,
|
| 534 |
+
"refresh_token": self.refresh_token,
|
| 535 |
+
"token_uri": self.token_uri,
|
| 536 |
+
"client_id": self.client_id,
|
| 537 |
+
"client_secret": self.client_secret,
|
| 538 |
+
"scopes": self.scopes,
|
| 539 |
+
"rapt_token": self.rapt_token,
|
| 540 |
+
"universe_domain": self._universe_domain,
|
| 541 |
+
"account": self._account,
|
| 542 |
+
}
|
| 543 |
+
if self.expiry: # flatten expiry timestamp
|
| 544 |
+
prep["expiry"] = self.expiry.isoformat() + "Z"
|
| 545 |
+
|
| 546 |
+
# Remove empty entries (those which are None)
|
| 547 |
+
prep = {k: v for k, v in prep.items() if v is not None}
|
| 548 |
+
|
| 549 |
+
# Remove entries that explicitely need to be removed
|
| 550 |
+
if strip is not None:
|
| 551 |
+
prep = {k: v for k, v in prep.items() if k not in strip}
|
| 552 |
+
|
| 553 |
+
return json.dumps(prep)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class UserAccessTokenCredentials(credentials.CredentialsWithQuotaProject):
|
| 557 |
+
"""Access token credentials for user account.
|
| 558 |
+
|
| 559 |
+
Obtain the access token for a given user account or the current active
|
| 560 |
+
user account with the ``gcloud auth print-access-token`` command.
|
| 561 |
+
|
| 562 |
+
Args:
|
| 563 |
+
account (Optional[str]): Account to get the access token for. If not
|
| 564 |
+
specified, the current active account will be used.
|
| 565 |
+
quota_project_id (Optional[str]): The project ID used for quota
|
| 566 |
+
and billing.
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
def __init__(self, account=None, quota_project_id=None):
|
| 570 |
+
warnings.warn(
|
| 571 |
+
"UserAccessTokenCredentials is deprecated, please use "
|
| 572 |
+
"google.oauth2.credentials.Credentials instead. To use "
|
| 573 |
+
"that credential type, simply run "
|
| 574 |
+
"`gcloud auth application-default login` and let the "
|
| 575 |
+
"client libraries pick up the application default credentials."
|
| 576 |
+
)
|
| 577 |
+
super(UserAccessTokenCredentials, self).__init__()
|
| 578 |
+
self._account = account
|
| 579 |
+
self._quota_project_id = quota_project_id
|
| 580 |
+
|
| 581 |
+
def with_account(self, account):
|
| 582 |
+
"""Create a new instance with the given account.
|
| 583 |
+
|
| 584 |
+
Args:
|
| 585 |
+
account (str): Account to get the access token for.
|
| 586 |
+
|
| 587 |
+
Returns:
|
| 588 |
+
google.oauth2.credentials.UserAccessTokenCredentials: The created
|
| 589 |
+
credentials with the given account.
|
| 590 |
+
"""
|
| 591 |
+
return self.__class__(account=account, quota_project_id=self._quota_project_id)
|
| 592 |
+
|
| 593 |
+
@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
|
| 594 |
+
def with_quota_project(self, quota_project_id):
|
| 595 |
+
return self.__class__(account=self._account, quota_project_id=quota_project_id)
|
| 596 |
+
|
| 597 |
+
def refresh(self, request):
|
| 598 |
+
"""Refreshes the access token.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
request (google.auth.transport.Request): This argument is required
|
| 602 |
+
by the base class interface but not used in this implementation,
|
| 603 |
+
so just set it to `None`.
|
| 604 |
+
|
| 605 |
+
Raises:
|
| 606 |
+
google.auth.exceptions.UserAccessTokenError: If the access token
|
| 607 |
+
refresh failed.
|
| 608 |
+
"""
|
| 609 |
+
self.token = _cloud_sdk.get_auth_access_token(self._account)
|
| 610 |
+
|
| 611 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 612 |
+
def before_request(self, request, method, url, headers):
|
| 613 |
+
self.refresh(request)
|
| 614 |
+
self.apply(headers)
|
lib/python3.10/site-packages/google/oauth2/gdch_credentials.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"""Experimental GDCH credentials support.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import datetime
|
| 19 |
+
|
| 20 |
+
from google.auth import _helpers
|
| 21 |
+
from google.auth import _service_account_info
|
| 22 |
+
from google.auth import credentials
|
| 23 |
+
from google.auth import exceptions
|
| 24 |
+
from google.auth import jwt
|
| 25 |
+
from google.oauth2 import _client
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
TOKEN_EXCHANGE_TYPE = "urn:ietf:params:oauth:token-type:token-exchange"
|
| 29 |
+
ACCESS_TOKEN_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
|
| 30 |
+
SERVICE_ACCOUNT_TOKEN_TYPE = "urn:k8s:params:oauth:token-type:serviceaccount"
|
| 31 |
+
JWT_LIFETIME = datetime.timedelta(seconds=3600) # 1 hour
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ServiceAccountCredentials(credentials.Credentials):
|
| 35 |
+
"""Credentials for GDCH (`Google Distributed Cloud Hosted`_) for service
|
| 36 |
+
account users.
|
| 37 |
+
|
| 38 |
+
.. _Google Distributed Cloud Hosted:
|
| 39 |
+
https://cloud.google.com/blog/topics/hybrid-cloud/\
|
| 40 |
+
announcing-google-distributed-cloud-edge-and-hosted
|
| 41 |
+
|
| 42 |
+
To create a GDCH service account credential, first create a JSON file of
|
| 43 |
+
the following format::
|
| 44 |
+
|
| 45 |
+
{
|
| 46 |
+
"type": "gdch_service_account",
|
| 47 |
+
"format_version": "1",
|
| 48 |
+
"project": "<project name>",
|
| 49 |
+
"private_key_id": "<key id>",
|
| 50 |
+
"private_key": "-----BEGIN EC PRIVATE KEY-----\n<key bytes>\n-----END EC PRIVATE KEY-----\n",
|
| 51 |
+
"name": "<service identity name>",
|
| 52 |
+
"ca_cert_path": "<CA cert path>",
|
| 53 |
+
"token_uri": "https://service-identity.<Domain>/authenticate"
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
The "format_version" field stands for the format of the JSON file. For now
|
| 57 |
+
it is always "1". The `private_key_id` and `private_key` is used for signing.
|
| 58 |
+
The `ca_cert_path` is used for token server TLS certificate verification.
|
| 59 |
+
|
| 60 |
+
After the JSON file is created, set `GOOGLE_APPLICATION_CREDENTIALS` environment
|
| 61 |
+
variable to the JSON file path, then use the following code to create the
|
| 62 |
+
credential::
|
| 63 |
+
|
| 64 |
+
import google.auth
|
| 65 |
+
|
| 66 |
+
credential, _ = google.auth.default()
|
| 67 |
+
credential = credential.with_gdch_audience("<the audience>")
|
| 68 |
+
|
| 69 |
+
We can also create the credential directly::
|
| 70 |
+
|
| 71 |
+
from google.oauth import gdch_credentials
|
| 72 |
+
|
| 73 |
+
credential = gdch_credentials.ServiceAccountCredentials.from_service_account_file("<the json file path>")
|
| 74 |
+
credential = credential.with_gdch_audience("<the audience>")
|
| 75 |
+
|
| 76 |
+
The token is obtained in the following way. This class first creates a
|
| 77 |
+
self signed JWT. It uses the `name` value as the `iss` and `sub` claim, and
|
| 78 |
+
the `token_uri` as the `aud` claim, and signs the JWT with the `private_key`.
|
| 79 |
+
It then sends the JWT to the `token_uri` to exchange a final token for
|
| 80 |
+
`audience`.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self, signer, service_identity_name, project, audience, token_uri, ca_cert_path
|
| 85 |
+
):
|
| 86 |
+
"""
|
| 87 |
+
Args:
|
| 88 |
+
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
|
| 89 |
+
service_identity_name (str): The service identity name. It will be
|
| 90 |
+
used as the `iss` and `sub` claim in the self signed JWT.
|
| 91 |
+
project (str): The project.
|
| 92 |
+
audience (str): The audience for the final token.
|
| 93 |
+
token_uri (str): The token server uri.
|
| 94 |
+
ca_cert_path (str): The CA cert path for token server side TLS
|
| 95 |
+
certificate verification. If the token server uses well known
|
| 96 |
+
CA, then this parameter can be `None`.
|
| 97 |
+
"""
|
| 98 |
+
super(ServiceAccountCredentials, self).__init__()
|
| 99 |
+
self._signer = signer
|
| 100 |
+
self._service_identity_name = service_identity_name
|
| 101 |
+
self._project = project
|
| 102 |
+
self._audience = audience
|
| 103 |
+
self._token_uri = token_uri
|
| 104 |
+
self._ca_cert_path = ca_cert_path
|
| 105 |
+
|
| 106 |
+
def _create_jwt(self):
|
| 107 |
+
now = _helpers.utcnow()
|
| 108 |
+
expiry = now + JWT_LIFETIME
|
| 109 |
+
iss_sub_value = "system:serviceaccount:{}:{}".format(
|
| 110 |
+
self._project, self._service_identity_name
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
payload = {
|
| 114 |
+
"iss": iss_sub_value,
|
| 115 |
+
"sub": iss_sub_value,
|
| 116 |
+
"aud": self._token_uri,
|
| 117 |
+
"iat": _helpers.datetime_to_secs(now),
|
| 118 |
+
"exp": _helpers.datetime_to_secs(expiry),
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
return _helpers.from_bytes(jwt.encode(self._signer, payload))
|
| 122 |
+
|
| 123 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 124 |
+
def refresh(self, request):
|
| 125 |
+
import google.auth.transport.requests
|
| 126 |
+
|
| 127 |
+
if not isinstance(request, google.auth.transport.requests.Request):
|
| 128 |
+
raise exceptions.RefreshError(
|
| 129 |
+
"For GDCH service account credentials, request must be a google.auth.transport.requests.Request object"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Create a self signed JWT, and do token exchange.
|
| 133 |
+
jwt_token = self._create_jwt()
|
| 134 |
+
request_body = {
|
| 135 |
+
"grant_type": TOKEN_EXCHANGE_TYPE,
|
| 136 |
+
"audience": self._audience,
|
| 137 |
+
"requested_token_type": ACCESS_TOKEN_TOKEN_TYPE,
|
| 138 |
+
"subject_token": jwt_token,
|
| 139 |
+
"subject_token_type": SERVICE_ACCOUNT_TOKEN_TYPE,
|
| 140 |
+
}
|
| 141 |
+
response_data = _client._token_endpoint_request(
|
| 142 |
+
request,
|
| 143 |
+
self._token_uri,
|
| 144 |
+
request_body,
|
| 145 |
+
access_token=None,
|
| 146 |
+
use_json=True,
|
| 147 |
+
verify=self._ca_cert_path,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
self.token, _, self.expiry, _ = _client._handle_refresh_grant_response(
|
| 151 |
+
response_data, None
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
def with_gdch_audience(self, audience):
|
| 155 |
+
"""Create a copy of GDCH credentials with the specified audience.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
audience (str): The intended audience for GDCH credentials.
|
| 159 |
+
"""
|
| 160 |
+
return self.__class__(
|
| 161 |
+
self._signer,
|
| 162 |
+
self._service_identity_name,
|
| 163 |
+
self._project,
|
| 164 |
+
audience,
|
| 165 |
+
self._token_uri,
|
| 166 |
+
self._ca_cert_path,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
@classmethod
|
| 170 |
+
def _from_signer_and_info(cls, signer, info):
|
| 171 |
+
"""Creates a Credentials instance from a signer and service account
|
| 172 |
+
info.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
|
| 176 |
+
info (Mapping[str, str]): The service account info.
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
google.oauth2.gdch_credentials.ServiceAccountCredentials: The constructed
|
| 180 |
+
credentials.
|
| 181 |
+
|
| 182 |
+
Raises:
|
| 183 |
+
ValueError: If the info is not in the expected format.
|
| 184 |
+
"""
|
| 185 |
+
if info["format_version"] != "1":
|
| 186 |
+
raise ValueError("Only format version 1 is supported")
|
| 187 |
+
|
| 188 |
+
return cls(
|
| 189 |
+
signer,
|
| 190 |
+
info["name"], # service_identity_name
|
| 191 |
+
info["project"],
|
| 192 |
+
None, # audience
|
| 193 |
+
info["token_uri"],
|
| 194 |
+
info.get("ca_cert_path", None),
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
@classmethod
|
| 198 |
+
def from_service_account_info(cls, info):
|
| 199 |
+
"""Creates a Credentials instance from parsed service account info.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
info (Mapping[str, str]): The service account info in Google
|
| 203 |
+
format.
|
| 204 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
google.oauth2.gdch_credentials.ServiceAccountCredentials: The constructed
|
| 208 |
+
credentials.
|
| 209 |
+
|
| 210 |
+
Raises:
|
| 211 |
+
ValueError: If the info is not in the expected format.
|
| 212 |
+
"""
|
| 213 |
+
signer = _service_account_info.from_dict(
|
| 214 |
+
info,
|
| 215 |
+
require=[
|
| 216 |
+
"format_version",
|
| 217 |
+
"private_key_id",
|
| 218 |
+
"private_key",
|
| 219 |
+
"name",
|
| 220 |
+
"project",
|
| 221 |
+
"token_uri",
|
| 222 |
+
],
|
| 223 |
+
use_rsa_signer=False,
|
| 224 |
+
)
|
| 225 |
+
return cls._from_signer_and_info(signer, info)
|
| 226 |
+
|
| 227 |
+
@classmethod
|
| 228 |
+
def from_service_account_file(cls, filename):
|
| 229 |
+
"""Creates a Credentials instance from a service account json file.
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
filename (str): The path to the service account json file.
|
| 233 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 234 |
+
|
| 235 |
+
Returns:
|
| 236 |
+
google.oauth2.gdch_credentials.ServiceAccountCredentials: The constructed
|
| 237 |
+
credentials.
|
| 238 |
+
"""
|
| 239 |
+
info, signer = _service_account_info.from_filename(
|
| 240 |
+
filename,
|
| 241 |
+
require=[
|
| 242 |
+
"format_version",
|
| 243 |
+
"private_key_id",
|
| 244 |
+
"private_key",
|
| 245 |
+
"name",
|
| 246 |
+
"project",
|
| 247 |
+
"token_uri",
|
| 248 |
+
],
|
| 249 |
+
use_rsa_signer=False,
|
| 250 |
+
)
|
| 251 |
+
return cls._from_signer_and_info(signer, info)
|
lib/python3.10/site-packages/google/oauth2/id_token.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ID Token helpers.
|
| 16 |
+
|
| 17 |
+
Provides support for verifying `OpenID Connect ID Tokens`_, especially ones
|
| 18 |
+
generated by Google infrastructure.
|
| 19 |
+
|
| 20 |
+
To parse and verify an ID Token issued by Google's OAuth 2.0 authorization
|
| 21 |
+
server use :func:`verify_oauth2_token`. To verify an ID Token issued by
|
| 22 |
+
Firebase, use :func:`verify_firebase_token`.
|
| 23 |
+
|
| 24 |
+
A general purpose ID Token verifier is available as :func:`verify_token`.
|
| 25 |
+
|
| 26 |
+
Example::
|
| 27 |
+
|
| 28 |
+
from google.oauth2 import id_token
|
| 29 |
+
from google.auth.transport import requests
|
| 30 |
+
|
| 31 |
+
request = requests.Request()
|
| 32 |
+
|
| 33 |
+
id_info = id_token.verify_oauth2_token(
|
| 34 |
+
token, request, 'my-client-id.example.com')
|
| 35 |
+
|
| 36 |
+
userid = id_info['sub']
|
| 37 |
+
|
| 38 |
+
By default, this will re-fetch certificates for each verification. Because
|
| 39 |
+
Google's public keys are only changed infrequently (on the order of once per
|
| 40 |
+
day), you may wish to take advantage of caching to reduce latency and the
|
| 41 |
+
potential for network errors. This can be accomplished using an external
|
| 42 |
+
library like `CacheControl`_ to create a cache-aware
|
| 43 |
+
:class:`google.auth.transport.Request`::
|
| 44 |
+
|
| 45 |
+
import cachecontrol
|
| 46 |
+
import google.auth.transport.requests
|
| 47 |
+
import requests
|
| 48 |
+
|
| 49 |
+
session = requests.session()
|
| 50 |
+
cached_session = cachecontrol.CacheControl(session)
|
| 51 |
+
request = google.auth.transport.requests.Request(session=cached_session)
|
| 52 |
+
|
| 53 |
+
.. _OpenID Connect ID Tokens:
|
| 54 |
+
http://openid.net/specs/openid-connect-core-1_0.html#IDToken
|
| 55 |
+
.. _CacheControl: https://cachecontrol.readthedocs.io
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
import http.client as http_client
|
| 59 |
+
import json
|
| 60 |
+
import os
|
| 61 |
+
|
| 62 |
+
from google.auth import environment_vars
|
| 63 |
+
from google.auth import exceptions
|
| 64 |
+
from google.auth import jwt
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# The URL that provides public certificates for verifying ID tokens issued
|
| 68 |
+
# by Google's OAuth 2.0 authorization server.
|
| 69 |
+
_GOOGLE_OAUTH2_CERTS_URL = "https://www.googleapis.com/oauth2/v1/certs"
|
| 70 |
+
|
| 71 |
+
# The URL that provides public certificates for verifying ID tokens issued
|
| 72 |
+
# by Firebase and the Google APIs infrastructure
|
| 73 |
+
_GOOGLE_APIS_CERTS_URL = (
|
| 74 |
+
"https://www.googleapis.com/robot/v1/metadata/x509"
|
| 75 |
+
"/securetoken@system.gserviceaccount.com"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
_GOOGLE_ISSUERS = ["accounts.google.com", "https://accounts.google.com"]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _fetch_certs(request, certs_url):
|
| 82 |
+
"""Fetches certificates.
|
| 83 |
+
|
| 84 |
+
Google-style cerificate endpoints return JSON in the format of
|
| 85 |
+
``{'key id': 'x509 certificate'}`` or a certificate array according
|
| 86 |
+
to the JWK spec (see https://tools.ietf.org/html/rfc7517).
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
request (google.auth.transport.Request): The object used to make
|
| 90 |
+
HTTP requests.
|
| 91 |
+
certs_url (str): The certificate endpoint URL.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
Mapping[str, str] | Mapping[str, list]: A mapping of public keys
|
| 95 |
+
in x.509 or JWK spec.
|
| 96 |
+
"""
|
| 97 |
+
response = request(certs_url, method="GET")
|
| 98 |
+
|
| 99 |
+
if response.status != http_client.OK:
|
| 100 |
+
raise exceptions.TransportError(
|
| 101 |
+
"Could not fetch certificates at {}".format(certs_url)
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
return json.loads(response.data.decode("utf-8"))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def verify_token(
|
| 108 |
+
id_token,
|
| 109 |
+
request,
|
| 110 |
+
audience=None,
|
| 111 |
+
certs_url=_GOOGLE_OAUTH2_CERTS_URL,
|
| 112 |
+
clock_skew_in_seconds=0,
|
| 113 |
+
):
|
| 114 |
+
"""Verifies an ID token and returns the decoded token.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
id_token (Union[str, bytes]): The encoded token.
|
| 118 |
+
request (google.auth.transport.Request): The object used to make
|
| 119 |
+
HTTP requests.
|
| 120 |
+
audience (str or list): The audience or audiences that this token is
|
| 121 |
+
intended for. If None then the audience is not verified.
|
| 122 |
+
certs_url (str): The URL that specifies the certificates to use to
|
| 123 |
+
verify the token. This URL should return JSON in the format of
|
| 124 |
+
``{'key id': 'x509 certificate'}`` or a certificate array according to
|
| 125 |
+
the JWK spec (see https://tools.ietf.org/html/rfc7517).
|
| 126 |
+
clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
|
| 127 |
+
validation.
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Mapping[str, Any]: The decoded token.
|
| 131 |
+
"""
|
| 132 |
+
certs = _fetch_certs(request, certs_url)
|
| 133 |
+
|
| 134 |
+
if "keys" in certs:
|
| 135 |
+
try:
|
| 136 |
+
import jwt as jwt_lib # type: ignore
|
| 137 |
+
except ImportError as caught_exc: # pragma: NO COVER
|
| 138 |
+
raise ImportError(
|
| 139 |
+
"The pyjwt library is not installed, please install the pyjwt package to use the jwk certs format."
|
| 140 |
+
) from caught_exc
|
| 141 |
+
jwks_client = jwt_lib.PyJWKClient(certs_url)
|
| 142 |
+
signing_key = jwks_client.get_signing_key_from_jwt(id_token)
|
| 143 |
+
return jwt_lib.decode(
|
| 144 |
+
id_token,
|
| 145 |
+
signing_key.key,
|
| 146 |
+
algorithms=[signing_key.algorithm_name],
|
| 147 |
+
audience=audience,
|
| 148 |
+
)
|
| 149 |
+
else:
|
| 150 |
+
return jwt.decode(
|
| 151 |
+
id_token,
|
| 152 |
+
certs=certs,
|
| 153 |
+
audience=audience,
|
| 154 |
+
clock_skew_in_seconds=clock_skew_in_seconds,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def verify_oauth2_token(id_token, request, audience=None, clock_skew_in_seconds=0):
|
| 159 |
+
"""Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
id_token (Union[str, bytes]): The encoded token.
|
| 163 |
+
request (google.auth.transport.Request): The object used to make
|
| 164 |
+
HTTP requests.
|
| 165 |
+
audience (str): The audience that this token is intended for. This is
|
| 166 |
+
typically your application's OAuth 2.0 client ID. If None then the
|
| 167 |
+
audience is not verified.
|
| 168 |
+
clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
|
| 169 |
+
validation.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Mapping[str, Any]: The decoded token.
|
| 173 |
+
|
| 174 |
+
Raises:
|
| 175 |
+
exceptions.GoogleAuthError: If the issuer is invalid.
|
| 176 |
+
ValueError: If token verification fails
|
| 177 |
+
"""
|
| 178 |
+
idinfo = verify_token(
|
| 179 |
+
id_token,
|
| 180 |
+
request,
|
| 181 |
+
audience=audience,
|
| 182 |
+
certs_url=_GOOGLE_OAUTH2_CERTS_URL,
|
| 183 |
+
clock_skew_in_seconds=clock_skew_in_seconds,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
if idinfo["iss"] not in _GOOGLE_ISSUERS:
|
| 187 |
+
raise exceptions.GoogleAuthError(
|
| 188 |
+
"Wrong issuer. 'iss' should be one of the following: {}".format(
|
| 189 |
+
_GOOGLE_ISSUERS
|
| 190 |
+
)
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
return idinfo
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def verify_firebase_token(id_token, request, audience=None, clock_skew_in_seconds=0):
|
| 197 |
+
"""Verifies an ID Token issued by Firebase Authentication.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
id_token (Union[str, bytes]): The encoded token.
|
| 201 |
+
request (google.auth.transport.Request): The object used to make
|
| 202 |
+
HTTP requests.
|
| 203 |
+
audience (str): The audience that this token is intended for. This is
|
| 204 |
+
typically your Firebase application ID. If None then the audience
|
| 205 |
+
is not verified.
|
| 206 |
+
clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
|
| 207 |
+
validation.
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
Mapping[str, Any]: The decoded token.
|
| 211 |
+
"""
|
| 212 |
+
return verify_token(
|
| 213 |
+
id_token,
|
| 214 |
+
request,
|
| 215 |
+
audience=audience,
|
| 216 |
+
certs_url=_GOOGLE_APIS_CERTS_URL,
|
| 217 |
+
clock_skew_in_seconds=clock_skew_in_seconds,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def fetch_id_token_credentials(audience, request=None):
|
| 222 |
+
"""Create the ID Token credentials from the current environment.
|
| 223 |
+
|
| 224 |
+
This function acquires ID token from the environment in the following order.
|
| 225 |
+
See https://google.aip.dev/auth/4110.
|
| 226 |
+
|
| 227 |
+
1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
|
| 228 |
+
to the path of a valid service account JSON file, then ID token is
|
| 229 |
+
acquired using this service account credentials.
|
| 230 |
+
2. If the application is running in Compute Engine, App Engine or Cloud Run,
|
| 231 |
+
then the ID token are obtained from the metadata server.
|
| 232 |
+
3. If metadata server doesn't exist and no valid service account credentials
|
| 233 |
+
are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will
|
| 234 |
+
be raised.
|
| 235 |
+
|
| 236 |
+
Example::
|
| 237 |
+
|
| 238 |
+
import google.oauth2.id_token
|
| 239 |
+
import google.auth.transport.requests
|
| 240 |
+
|
| 241 |
+
request = google.auth.transport.requests.Request()
|
| 242 |
+
target_audience = "https://pubsub.googleapis.com"
|
| 243 |
+
|
| 244 |
+
# Create ID token credentials.
|
| 245 |
+
credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request)
|
| 246 |
+
|
| 247 |
+
# Refresh the credential to obtain an ID token.
|
| 248 |
+
credentials.refresh(request)
|
| 249 |
+
|
| 250 |
+
id_token = credentials.token
|
| 251 |
+
id_token_expiry = credentials.expiry
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
audience (str): The audience that this ID token is intended for.
|
| 255 |
+
request (Optional[google.auth.transport.Request]): A callable used to make
|
| 256 |
+
HTTP requests. A request object will be created if not provided.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
google.auth.credentials.Credentials: The ID token credentials.
|
| 260 |
+
|
| 261 |
+
Raises:
|
| 262 |
+
~google.auth.exceptions.DefaultCredentialsError:
|
| 263 |
+
If metadata server doesn't exist and no valid service account
|
| 264 |
+
credentials are found.
|
| 265 |
+
"""
|
| 266 |
+
# 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
|
| 267 |
+
# variable.
|
| 268 |
+
credentials_filename = os.environ.get(environment_vars.CREDENTIALS)
|
| 269 |
+
if credentials_filename:
|
| 270 |
+
if not (
|
| 271 |
+
os.path.exists(credentials_filename)
|
| 272 |
+
and os.path.isfile(credentials_filename)
|
| 273 |
+
):
|
| 274 |
+
raise exceptions.DefaultCredentialsError(
|
| 275 |
+
"GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid."
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
with open(credentials_filename, "r") as f:
|
| 280 |
+
from google.oauth2 import service_account
|
| 281 |
+
|
| 282 |
+
info = json.load(f)
|
| 283 |
+
if info.get("type") == "service_account":
|
| 284 |
+
return service_account.IDTokenCredentials.from_service_account_info(
|
| 285 |
+
info, target_audience=audience
|
| 286 |
+
)
|
| 287 |
+
except ValueError as caught_exc:
|
| 288 |
+
new_exc = exceptions.DefaultCredentialsError(
|
| 289 |
+
"GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.",
|
| 290 |
+
caught_exc,
|
| 291 |
+
)
|
| 292 |
+
raise new_exc from caught_exc
|
| 293 |
+
|
| 294 |
+
# 2. Try to fetch ID token from metada server if it exists. The code
|
| 295 |
+
# works for GAE and Cloud Run metadata server as well.
|
| 296 |
+
try:
|
| 297 |
+
from google.auth import compute_engine
|
| 298 |
+
from google.auth.compute_engine import _metadata
|
| 299 |
+
|
| 300 |
+
# Create a request object if not provided.
|
| 301 |
+
if not request:
|
| 302 |
+
import google.auth.transport.requests
|
| 303 |
+
|
| 304 |
+
request = google.auth.transport.requests.Request()
|
| 305 |
+
|
| 306 |
+
if _metadata.ping(request):
|
| 307 |
+
return compute_engine.IDTokenCredentials(
|
| 308 |
+
request, audience, use_metadata_identity_endpoint=True
|
| 309 |
+
)
|
| 310 |
+
except (ImportError, exceptions.TransportError):
|
| 311 |
+
pass
|
| 312 |
+
|
| 313 |
+
raise exceptions.DefaultCredentialsError(
|
| 314 |
+
"Neither metadata server or valid service account credentials are found."
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def fetch_id_token(request, audience):
|
| 319 |
+
"""Fetch the ID Token from the current environment.
|
| 320 |
+
|
| 321 |
+
This function acquires ID token from the environment in the following order.
|
| 322 |
+
See https://google.aip.dev/auth/4110.
|
| 323 |
+
|
| 324 |
+
1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
|
| 325 |
+
to the path of a valid service account JSON file, then ID token is
|
| 326 |
+
acquired using this service account credentials.
|
| 327 |
+
2. If the application is running in Compute Engine, App Engine or Cloud Run,
|
| 328 |
+
then the ID token are obtained from the metadata server.
|
| 329 |
+
3. If metadata server doesn't exist and no valid service account credentials
|
| 330 |
+
are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will
|
| 331 |
+
be raised.
|
| 332 |
+
|
| 333 |
+
Example::
|
| 334 |
+
|
| 335 |
+
import google.oauth2.id_token
|
| 336 |
+
import google.auth.transport.requests
|
| 337 |
+
|
| 338 |
+
request = google.auth.transport.requests.Request()
|
| 339 |
+
target_audience = "https://pubsub.googleapis.com"
|
| 340 |
+
|
| 341 |
+
id_token = google.oauth2.id_token.fetch_id_token(request, target_audience)
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
request (google.auth.transport.Request): A callable used to make
|
| 345 |
+
HTTP requests.
|
| 346 |
+
audience (str): The audience that this ID token is intended for.
|
| 347 |
+
|
| 348 |
+
Returns:
|
| 349 |
+
str: The ID token.
|
| 350 |
+
|
| 351 |
+
Raises:
|
| 352 |
+
~google.auth.exceptions.DefaultCredentialsError:
|
| 353 |
+
If metadata server doesn't exist and no valid service account
|
| 354 |
+
credentials are found.
|
| 355 |
+
"""
|
| 356 |
+
id_token_credentials = fetch_id_token_credentials(audience, request=request)
|
| 357 |
+
id_token_credentials.refresh(request)
|
| 358 |
+
return id_token_credentials.token
|
lib/python3.10/site-packages/google/oauth2/py.typed
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Marker file for PEP 561.
|
| 2 |
+
# The google-oauth2 package uses inline types.
|
lib/python3.10/site-packages/google/oauth2/reauth.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 |
+
"""A module that provides functions for handling rapt authentication.
|
| 16 |
+
|
| 17 |
+
Reauth is a process of obtaining additional authentication (such as password,
|
| 18 |
+
security token, etc.) while refreshing OAuth 2.0 credentials for a user.
|
| 19 |
+
|
| 20 |
+
Credentials that use the Reauth flow must have the reauth scope,
|
| 21 |
+
``https://www.googleapis.com/auth/accounts.reauth``.
|
| 22 |
+
|
| 23 |
+
This module provides a high-level function for executing the Reauth process,
|
| 24 |
+
:func:`refresh_grant`, and lower-level helpers for doing the individual
|
| 25 |
+
steps of the reauth process.
|
| 26 |
+
|
| 27 |
+
Those steps are:
|
| 28 |
+
|
| 29 |
+
1. Obtaining a list of challenges from the reauth server.
|
| 30 |
+
2. Running through each challenge and sending the result back to the reauth
|
| 31 |
+
server.
|
| 32 |
+
3. Refreshing the access token using the returned rapt token.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import sys
|
| 36 |
+
|
| 37 |
+
from google.auth import exceptions
|
| 38 |
+
from google.auth import metrics
|
| 39 |
+
from google.oauth2 import _client
|
| 40 |
+
from google.oauth2 import challenges
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
_REAUTH_SCOPE = "https://www.googleapis.com/auth/accounts.reauth"
|
| 44 |
+
_REAUTH_API = "https://reauth.googleapis.com/v2/sessions"
|
| 45 |
+
|
| 46 |
+
_REAUTH_NEEDED_ERROR = "invalid_grant"
|
| 47 |
+
_REAUTH_NEEDED_ERROR_INVALID_RAPT = "invalid_rapt"
|
| 48 |
+
_REAUTH_NEEDED_ERROR_RAPT_REQUIRED = "rapt_required"
|
| 49 |
+
|
| 50 |
+
_AUTHENTICATED = "AUTHENTICATED"
|
| 51 |
+
_CHALLENGE_REQUIRED = "CHALLENGE_REQUIRED"
|
| 52 |
+
_CHALLENGE_PENDING = "CHALLENGE_PENDING"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Override this global variable to set custom max number of rounds of reauth
|
| 56 |
+
# challenges should be run.
|
| 57 |
+
RUN_CHALLENGE_RETRY_LIMIT = 5
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def is_interactive():
|
| 61 |
+
"""Check if we are in an interractive environment.
|
| 62 |
+
|
| 63 |
+
Override this function with a different logic if you are using this library
|
| 64 |
+
outside a CLI.
|
| 65 |
+
|
| 66 |
+
If the rapt token needs refreshing, the user needs to answer the challenges.
|
| 67 |
+
If the user is not in an interractive environment, the challenges can not
|
| 68 |
+
be answered and we just wait for timeout for no reason.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
bool: True if is interactive environment, False otherwise.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
return sys.stdin.isatty()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _get_challenges(
|
| 78 |
+
request, supported_challenge_types, access_token, requested_scopes=None
|
| 79 |
+
):
|
| 80 |
+
"""Does initial request to reauth API to get the challenges.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
request (google.auth.transport.Request): A callable used to make
|
| 84 |
+
HTTP requests.
|
| 85 |
+
supported_challenge_types (Sequence[str]): list of challenge names
|
| 86 |
+
supported by the manager.
|
| 87 |
+
access_token (str): Access token with reauth scopes.
|
| 88 |
+
requested_scopes (Optional(Sequence[str])): Authorized scopes for the credentials.
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
dict: The response from the reauth API.
|
| 92 |
+
"""
|
| 93 |
+
body = {"supportedChallengeTypes": supported_challenge_types}
|
| 94 |
+
if requested_scopes:
|
| 95 |
+
body["oauthScopesForDomainPolicyLookup"] = requested_scopes
|
| 96 |
+
metrics_header = {metrics.API_CLIENT_HEADER: metrics.reauth_start()}
|
| 97 |
+
|
| 98 |
+
return _client._token_endpoint_request(
|
| 99 |
+
request,
|
| 100 |
+
_REAUTH_API + ":start",
|
| 101 |
+
body,
|
| 102 |
+
access_token=access_token,
|
| 103 |
+
use_json=True,
|
| 104 |
+
headers=metrics_header,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _send_challenge_result(
|
| 109 |
+
request, session_id, challenge_id, client_input, access_token
|
| 110 |
+
):
|
| 111 |
+
"""Attempt to refresh access token by sending next challenge result.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
request (google.auth.transport.Request): A callable used to make
|
| 115 |
+
HTTP requests.
|
| 116 |
+
session_id (str): session id returned by the initial reauth call.
|
| 117 |
+
challenge_id (str): challenge id returned by the initial reauth call.
|
| 118 |
+
client_input: dict with a challenge-specific client input. For example:
|
| 119 |
+
``{'credential': password}`` for password challenge.
|
| 120 |
+
access_token (str): Access token with reauth scopes.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
dict: The response from the reauth API.
|
| 124 |
+
"""
|
| 125 |
+
body = {
|
| 126 |
+
"sessionId": session_id,
|
| 127 |
+
"challengeId": challenge_id,
|
| 128 |
+
"action": "RESPOND",
|
| 129 |
+
"proposalResponse": client_input,
|
| 130 |
+
}
|
| 131 |
+
metrics_header = {metrics.API_CLIENT_HEADER: metrics.reauth_continue()}
|
| 132 |
+
|
| 133 |
+
return _client._token_endpoint_request(
|
| 134 |
+
request,
|
| 135 |
+
_REAUTH_API + "/{}:continue".format(session_id),
|
| 136 |
+
body,
|
| 137 |
+
access_token=access_token,
|
| 138 |
+
use_json=True,
|
| 139 |
+
headers=metrics_header,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _run_next_challenge(msg, request, access_token):
|
| 144 |
+
"""Get the next challenge from msg and run it.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
msg (dict): Reauth API response body (either from the initial request to
|
| 148 |
+
https://reauth.googleapis.com/v2/sessions:start or from sending the
|
| 149 |
+
previous challenge response to
|
| 150 |
+
https://reauth.googleapis.com/v2/sessions/id:continue)
|
| 151 |
+
request (google.auth.transport.Request): A callable used to make
|
| 152 |
+
HTTP requests.
|
| 153 |
+
access_token (str): reauth access token
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
dict: The response from the reauth API.
|
| 157 |
+
|
| 158 |
+
Raises:
|
| 159 |
+
google.auth.exceptions.ReauthError: if reauth failed.
|
| 160 |
+
"""
|
| 161 |
+
for challenge in msg["challenges"]:
|
| 162 |
+
if challenge["status"] != "READY":
|
| 163 |
+
# Skip non-activated challenges.
|
| 164 |
+
continue
|
| 165 |
+
c = challenges.AVAILABLE_CHALLENGES.get(challenge["challengeType"], None)
|
| 166 |
+
if not c:
|
| 167 |
+
raise exceptions.ReauthFailError(
|
| 168 |
+
"Unsupported challenge type {0}. Supported types: {1}".format(
|
| 169 |
+
challenge["challengeType"],
|
| 170 |
+
",".join(list(challenges.AVAILABLE_CHALLENGES.keys())),
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
if not c.is_locally_eligible:
|
| 174 |
+
raise exceptions.ReauthFailError(
|
| 175 |
+
"Challenge {0} is not locally eligible".format(
|
| 176 |
+
challenge["challengeType"]
|
| 177 |
+
)
|
| 178 |
+
)
|
| 179 |
+
client_input = c.obtain_challenge_input(challenge)
|
| 180 |
+
if not client_input:
|
| 181 |
+
return None
|
| 182 |
+
return _send_challenge_result(
|
| 183 |
+
request,
|
| 184 |
+
msg["sessionId"],
|
| 185 |
+
challenge["challengeId"],
|
| 186 |
+
client_input,
|
| 187 |
+
access_token,
|
| 188 |
+
)
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _obtain_rapt(request, access_token, requested_scopes):
|
| 193 |
+
"""Given an http request method and reauth access token, get rapt token.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
request (google.auth.transport.Request): A callable used to make
|
| 197 |
+
HTTP requests.
|
| 198 |
+
access_token (str): reauth access token
|
| 199 |
+
requested_scopes (Sequence[str]): scopes required by the client application
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
str: The rapt token.
|
| 203 |
+
|
| 204 |
+
Raises:
|
| 205 |
+
google.auth.exceptions.ReauthError: if reauth failed
|
| 206 |
+
"""
|
| 207 |
+
msg = _get_challenges(
|
| 208 |
+
request,
|
| 209 |
+
list(challenges.AVAILABLE_CHALLENGES.keys()),
|
| 210 |
+
access_token,
|
| 211 |
+
requested_scopes,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if msg["status"] == _AUTHENTICATED:
|
| 215 |
+
return msg["encodedProofOfReauthToken"]
|
| 216 |
+
|
| 217 |
+
for _ in range(0, RUN_CHALLENGE_RETRY_LIMIT):
|
| 218 |
+
if not (
|
| 219 |
+
msg["status"] == _CHALLENGE_REQUIRED or msg["status"] == _CHALLENGE_PENDING
|
| 220 |
+
):
|
| 221 |
+
raise exceptions.ReauthFailError(
|
| 222 |
+
"Reauthentication challenge failed due to API error: {}".format(
|
| 223 |
+
msg["status"]
|
| 224 |
+
)
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
if not is_interactive():
|
| 228 |
+
raise exceptions.ReauthFailError(
|
| 229 |
+
"Reauthentication challenge could not be answered because you are not"
|
| 230 |
+
" in an interactive session."
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
msg = _run_next_challenge(msg, request, access_token)
|
| 234 |
+
|
| 235 |
+
if not msg:
|
| 236 |
+
raise exceptions.ReauthFailError("Failed to obtain rapt token.")
|
| 237 |
+
if msg["status"] == _AUTHENTICATED:
|
| 238 |
+
return msg["encodedProofOfReauthToken"]
|
| 239 |
+
|
| 240 |
+
# If we got here it means we didn't get authenticated.
|
| 241 |
+
raise exceptions.ReauthFailError("Failed to obtain rapt token.")
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def get_rapt_token(
|
| 245 |
+
request, client_id, client_secret, refresh_token, token_uri, scopes=None
|
| 246 |
+
):
|
| 247 |
+
"""Given an http request method and refresh_token, get rapt token.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
request (google.auth.transport.Request): A callable used to make
|
| 251 |
+
HTTP requests.
|
| 252 |
+
client_id (str): client id to get access token for reauth scope.
|
| 253 |
+
client_secret (str): client secret for the client_id
|
| 254 |
+
refresh_token (str): refresh token to refresh access token
|
| 255 |
+
token_uri (str): uri to refresh access token
|
| 256 |
+
scopes (Optional(Sequence[str])): scopes required by the client application
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
str: The rapt token.
|
| 260 |
+
Raises:
|
| 261 |
+
google.auth.exceptions.RefreshError: If reauth failed.
|
| 262 |
+
"""
|
| 263 |
+
sys.stderr.write("Reauthentication required.\n")
|
| 264 |
+
|
| 265 |
+
# Get access token for reauth.
|
| 266 |
+
access_token, _, _, _ = _client.refresh_grant(
|
| 267 |
+
request=request,
|
| 268 |
+
client_id=client_id,
|
| 269 |
+
client_secret=client_secret,
|
| 270 |
+
refresh_token=refresh_token,
|
| 271 |
+
token_uri=token_uri,
|
| 272 |
+
scopes=[_REAUTH_SCOPE],
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
# Get rapt token from reauth API.
|
| 276 |
+
rapt_token = _obtain_rapt(request, access_token, requested_scopes=scopes)
|
| 277 |
+
sys.stderr.write("Reauthentication successful.\n")
|
| 278 |
+
|
| 279 |
+
return rapt_token
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def refresh_grant(
|
| 283 |
+
request,
|
| 284 |
+
token_uri,
|
| 285 |
+
refresh_token,
|
| 286 |
+
client_id,
|
| 287 |
+
client_secret,
|
| 288 |
+
scopes=None,
|
| 289 |
+
rapt_token=None,
|
| 290 |
+
enable_reauth_refresh=False,
|
| 291 |
+
):
|
| 292 |
+
"""Implements the reauthentication flow.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
request (google.auth.transport.Request): A callable used to make
|
| 296 |
+
HTTP requests.
|
| 297 |
+
token_uri (str): The OAuth 2.0 authorizations server's token endpoint
|
| 298 |
+
URI.
|
| 299 |
+
refresh_token (str): The refresh token to use to get a new access
|
| 300 |
+
token.
|
| 301 |
+
client_id (str): The OAuth 2.0 application's client ID.
|
| 302 |
+
client_secret (str): The Oauth 2.0 appliaction's client secret.
|
| 303 |
+
scopes (Optional(Sequence[str])): Scopes to request. If present, all
|
| 304 |
+
scopes must be authorized for the refresh token. Useful if refresh
|
| 305 |
+
token has a wild card scope (e.g.
|
| 306 |
+
'https://www.googleapis.com/auth/any-api').
|
| 307 |
+
rapt_token (Optional(str)): The rapt token for reauth.
|
| 308 |
+
enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
|
| 309 |
+
should be used. The default value is False. This option is for
|
| 310 |
+
gcloud only, other users should use the default value.
|
| 311 |
+
|
| 312 |
+
Returns:
|
| 313 |
+
Tuple[str, Optional[str], Optional[datetime], Mapping[str, str], str]: The
|
| 314 |
+
access token, new refresh token, expiration, the additional data
|
| 315 |
+
returned by the token endpoint, and the rapt token.
|
| 316 |
+
|
| 317 |
+
Raises:
|
| 318 |
+
google.auth.exceptions.RefreshError: If the token endpoint returned
|
| 319 |
+
an error.
|
| 320 |
+
"""
|
| 321 |
+
body = {
|
| 322 |
+
"grant_type": _client._REFRESH_GRANT_TYPE,
|
| 323 |
+
"client_id": client_id,
|
| 324 |
+
"client_secret": client_secret,
|
| 325 |
+
"refresh_token": refresh_token,
|
| 326 |
+
}
|
| 327 |
+
if scopes:
|
| 328 |
+
body["scope"] = " ".join(scopes)
|
| 329 |
+
if rapt_token:
|
| 330 |
+
body["rapt"] = rapt_token
|
| 331 |
+
metrics_header = {metrics.API_CLIENT_HEADER: metrics.token_request_user()}
|
| 332 |
+
|
| 333 |
+
response_status_ok, response_data, retryable_error = _client._token_endpoint_request_no_throw(
|
| 334 |
+
request, token_uri, body, headers=metrics_header
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
if not response_status_ok and isinstance(response_data, str):
|
| 338 |
+
raise exceptions.RefreshError(response_data, retryable=False)
|
| 339 |
+
|
| 340 |
+
if (
|
| 341 |
+
not response_status_ok
|
| 342 |
+
and response_data.get("error") == _REAUTH_NEEDED_ERROR
|
| 343 |
+
and (
|
| 344 |
+
response_data.get("error_subtype") == _REAUTH_NEEDED_ERROR_INVALID_RAPT
|
| 345 |
+
or response_data.get("error_subtype") == _REAUTH_NEEDED_ERROR_RAPT_REQUIRED
|
| 346 |
+
)
|
| 347 |
+
):
|
| 348 |
+
if not enable_reauth_refresh:
|
| 349 |
+
raise exceptions.RefreshError(
|
| 350 |
+
"Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate."
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
rapt_token = get_rapt_token(
|
| 354 |
+
request, client_id, client_secret, refresh_token, token_uri, scopes=scopes
|
| 355 |
+
)
|
| 356 |
+
body["rapt"] = rapt_token
|
| 357 |
+
(
|
| 358 |
+
response_status_ok,
|
| 359 |
+
response_data,
|
| 360 |
+
retryable_error,
|
| 361 |
+
) = _client._token_endpoint_request_no_throw(
|
| 362 |
+
request, token_uri, body, headers=metrics_header
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
if not response_status_ok:
|
| 366 |
+
_client._handle_error_response(response_data, retryable_error)
|
| 367 |
+
return _client._handle_refresh_grant_response(response_data, refresh_token) + (
|
| 368 |
+
rapt_token,
|
| 369 |
+
)
|
lib/python3.10/site-packages/google/oauth2/service_account.py
ADDED
|
@@ -0,0 +1,847 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0
|
| 16 |
+
|
| 17 |
+
This module implements the JWT Profile for OAuth 2.0 Authorization Grants
|
| 18 |
+
as defined by `RFC 7523`_ with particular support for how this RFC is
|
| 19 |
+
implemented in Google's infrastructure. Google refers to these credentials
|
| 20 |
+
as *Service Accounts*.
|
| 21 |
+
|
| 22 |
+
Service accounts are used for server-to-server communication, such as
|
| 23 |
+
interactions between a web application server and a Google service. The
|
| 24 |
+
service account belongs to your application instead of to an individual end
|
| 25 |
+
user. In contrast to other OAuth 2.0 profiles, no users are involved and your
|
| 26 |
+
application "acts" as the service account.
|
| 27 |
+
|
| 28 |
+
Typically an application uses a service account when the application uses
|
| 29 |
+
Google APIs to work with its own data rather than a user's data. For example,
|
| 30 |
+
an application that uses Google Cloud Datastore for data persistence would use
|
| 31 |
+
a service account to authenticate its calls to the Google Cloud Datastore API.
|
| 32 |
+
However, an application that needs to access a user's Drive documents would
|
| 33 |
+
use the normal OAuth 2.0 profile.
|
| 34 |
+
|
| 35 |
+
Additionally, Google Apps domain administrators can grant service accounts
|
| 36 |
+
`domain-wide delegation`_ authority to access user data on behalf of users in
|
| 37 |
+
the domain.
|
| 38 |
+
|
| 39 |
+
This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used
|
| 40 |
+
in place of the usual authorization token returned during the standard
|
| 41 |
+
OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as
|
| 42 |
+
the acquired access token is used as the bearer token when making requests
|
| 43 |
+
using these credentials.
|
| 44 |
+
|
| 45 |
+
This profile differs from normal OAuth 2.0 profile because no user consent
|
| 46 |
+
step is required. The use of the private key allows this profile to assert
|
| 47 |
+
identity directly.
|
| 48 |
+
|
| 49 |
+
This profile also differs from the :mod:`google.auth.jwt` authentication
|
| 50 |
+
because the JWT credentials use the JWT directly as the bearer token. This
|
| 51 |
+
profile instead only uses the JWT to obtain an OAuth 2.0 access token. The
|
| 52 |
+
obtained OAuth 2.0 access token is used as the bearer token.
|
| 53 |
+
|
| 54 |
+
Domain-wide delegation
|
| 55 |
+
----------------------
|
| 56 |
+
|
| 57 |
+
Domain-wide delegation allows a service account to access user data on
|
| 58 |
+
behalf of any user in a Google Apps domain without consent from the user.
|
| 59 |
+
For example, an application that uses the Google Calendar API to add events to
|
| 60 |
+
the calendars of all users in a Google Apps domain would use a service account
|
| 61 |
+
to access the Google Calendar API on behalf of users.
|
| 62 |
+
|
| 63 |
+
The Google Apps administrator must explicitly authorize the service account to
|
| 64 |
+
do this. This authorization step is referred to as "delegating domain-wide
|
| 65 |
+
authority" to a service account.
|
| 66 |
+
|
| 67 |
+
You can use domain-wise delegation by creating a set of credentials with a
|
| 68 |
+
specific subject using :meth:`~Credentials.with_subject`.
|
| 69 |
+
|
| 70 |
+
.. _RFC 7523: https://tools.ietf.org/html/rfc7523
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
import copy
|
| 74 |
+
import datetime
|
| 75 |
+
|
| 76 |
+
from google.auth import _helpers
|
| 77 |
+
from google.auth import _service_account_info
|
| 78 |
+
from google.auth import credentials
|
| 79 |
+
from google.auth import exceptions
|
| 80 |
+
from google.auth import iam
|
| 81 |
+
from google.auth import jwt
|
| 82 |
+
from google.auth import metrics
|
| 83 |
+
from google.oauth2 import _client
|
| 84 |
+
|
| 85 |
+
_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
|
| 86 |
+
_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class Credentials(
|
| 90 |
+
credentials.Signing,
|
| 91 |
+
credentials.Scoped,
|
| 92 |
+
credentials.CredentialsWithQuotaProject,
|
| 93 |
+
credentials.CredentialsWithTokenUri,
|
| 94 |
+
):
|
| 95 |
+
"""Service account credentials
|
| 96 |
+
|
| 97 |
+
Usually, you'll create these credentials with one of the helper
|
| 98 |
+
constructors. To create credentials using a Google service account
|
| 99 |
+
private key JSON file::
|
| 100 |
+
|
| 101 |
+
credentials = service_account.Credentials.from_service_account_file(
|
| 102 |
+
'service-account.json')
|
| 103 |
+
|
| 104 |
+
Or if you already have the service account file loaded::
|
| 105 |
+
|
| 106 |
+
service_account_info = json.load(open('service_account.json'))
|
| 107 |
+
credentials = service_account.Credentials.from_service_account_info(
|
| 108 |
+
service_account_info)
|
| 109 |
+
|
| 110 |
+
Both helper methods pass on arguments to the constructor, so you can
|
| 111 |
+
specify additional scopes and a subject if necessary::
|
| 112 |
+
|
| 113 |
+
credentials = service_account.Credentials.from_service_account_file(
|
| 114 |
+
'service-account.json',
|
| 115 |
+
scopes=['email'],
|
| 116 |
+
subject='user@example.com')
|
| 117 |
+
|
| 118 |
+
The credentials are considered immutable. If you want to modify the scopes
|
| 119 |
+
or the subject used for delegation, use :meth:`with_scopes` or
|
| 120 |
+
:meth:`with_subject`::
|
| 121 |
+
|
| 122 |
+
scoped_credentials = credentials.with_scopes(['email'])
|
| 123 |
+
delegated_credentials = credentials.with_subject(subject)
|
| 124 |
+
|
| 125 |
+
To add a quota project, use :meth:`with_quota_project`::
|
| 126 |
+
|
| 127 |
+
credentials = credentials.with_quota_project('myproject-123')
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
def __init__(
|
| 131 |
+
self,
|
| 132 |
+
signer,
|
| 133 |
+
service_account_email,
|
| 134 |
+
token_uri,
|
| 135 |
+
scopes=None,
|
| 136 |
+
default_scopes=None,
|
| 137 |
+
subject=None,
|
| 138 |
+
project_id=None,
|
| 139 |
+
quota_project_id=None,
|
| 140 |
+
additional_claims=None,
|
| 141 |
+
always_use_jwt_access=False,
|
| 142 |
+
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
|
| 143 |
+
trust_boundary=None,
|
| 144 |
+
):
|
| 145 |
+
"""
|
| 146 |
+
Args:
|
| 147 |
+
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
|
| 148 |
+
service_account_email (str): The service account's email.
|
| 149 |
+
scopes (Sequence[str]): User-defined scopes to request during the
|
| 150 |
+
authorization grant.
|
| 151 |
+
default_scopes (Sequence[str]): Default scopes passed by a
|
| 152 |
+
Google client library. Use 'scopes' for user-defined scopes.
|
| 153 |
+
token_uri (str): The OAuth 2.0 Token URI.
|
| 154 |
+
subject (str): For domain-wide delegation, the email address of the
|
| 155 |
+
user to for which to request delegated access.
|
| 156 |
+
project_id (str): Project ID associated with the service account
|
| 157 |
+
credential.
|
| 158 |
+
quota_project_id (Optional[str]): The project ID used for quota and
|
| 159 |
+
billing.
|
| 160 |
+
additional_claims (Mapping[str, str]): Any additional claims for
|
| 161 |
+
the JWT assertion used in the authorization grant.
|
| 162 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 163 |
+
be always used.
|
| 164 |
+
universe_domain (str): The universe domain. The default
|
| 165 |
+
universe domain is googleapis.com. For default value self
|
| 166 |
+
signed jwt is used for token refresh.
|
| 167 |
+
trust_boundary (str): String representation of trust boundary meta.
|
| 168 |
+
|
| 169 |
+
.. note:: Typically one of the helper constructors
|
| 170 |
+
:meth:`from_service_account_file` or
|
| 171 |
+
:meth:`from_service_account_info` are used instead of calling the
|
| 172 |
+
constructor directly.
|
| 173 |
+
"""
|
| 174 |
+
super(Credentials, self).__init__()
|
| 175 |
+
|
| 176 |
+
self._cred_file_path = None
|
| 177 |
+
self._scopes = scopes
|
| 178 |
+
self._default_scopes = default_scopes
|
| 179 |
+
self._signer = signer
|
| 180 |
+
self._service_account_email = service_account_email
|
| 181 |
+
self._subject = subject
|
| 182 |
+
self._project_id = project_id
|
| 183 |
+
self._quota_project_id = quota_project_id
|
| 184 |
+
self._token_uri = token_uri
|
| 185 |
+
self._always_use_jwt_access = always_use_jwt_access
|
| 186 |
+
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 187 |
+
|
| 188 |
+
if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
|
| 189 |
+
self._always_use_jwt_access = True
|
| 190 |
+
|
| 191 |
+
self._jwt_credentials = None
|
| 192 |
+
|
| 193 |
+
if additional_claims is not None:
|
| 194 |
+
self._additional_claims = additional_claims
|
| 195 |
+
else:
|
| 196 |
+
self._additional_claims = {}
|
| 197 |
+
self._trust_boundary = {"locations": [], "encoded_locations": "0x0"}
|
| 198 |
+
|
| 199 |
+
@classmethod
|
| 200 |
+
def _from_signer_and_info(cls, signer, info, **kwargs):
|
| 201 |
+
"""Creates a Credentials instance from a signer and service account
|
| 202 |
+
info.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
|
| 206 |
+
info (Mapping[str, str]): The service account info.
|
| 207 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
google.auth.jwt.Credentials: The constructed credentials.
|
| 211 |
+
|
| 212 |
+
Raises:
|
| 213 |
+
ValueError: If the info is not in the expected format.
|
| 214 |
+
"""
|
| 215 |
+
return cls(
|
| 216 |
+
signer,
|
| 217 |
+
service_account_email=info["client_email"],
|
| 218 |
+
token_uri=info["token_uri"],
|
| 219 |
+
project_id=info.get("project_id"),
|
| 220 |
+
universe_domain=info.get(
|
| 221 |
+
"universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 222 |
+
),
|
| 223 |
+
trust_boundary=info.get("trust_boundary"),
|
| 224 |
+
**kwargs,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
@classmethod
|
| 228 |
+
def from_service_account_info(cls, info, **kwargs):
|
| 229 |
+
"""Creates a Credentials instance from parsed service account info.
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
info (Mapping[str, str]): The service account info in Google
|
| 233 |
+
format.
|
| 234 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 235 |
+
|
| 236 |
+
Returns:
|
| 237 |
+
google.auth.service_account.Credentials: The constructed
|
| 238 |
+
credentials.
|
| 239 |
+
|
| 240 |
+
Raises:
|
| 241 |
+
ValueError: If the info is not in the expected format.
|
| 242 |
+
"""
|
| 243 |
+
signer = _service_account_info.from_dict(
|
| 244 |
+
info, require=["client_email", "token_uri"]
|
| 245 |
+
)
|
| 246 |
+
return cls._from_signer_and_info(signer, info, **kwargs)
|
| 247 |
+
|
| 248 |
+
@classmethod
|
| 249 |
+
def from_service_account_file(cls, filename, **kwargs):
|
| 250 |
+
"""Creates a Credentials instance from a service account json file.
|
| 251 |
+
|
| 252 |
+
Args:
|
| 253 |
+
filename (str): The path to the service account json file.
|
| 254 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
google.auth.service_account.Credentials: The constructed
|
| 258 |
+
credentials.
|
| 259 |
+
"""
|
| 260 |
+
info, signer = _service_account_info.from_filename(
|
| 261 |
+
filename, require=["client_email", "token_uri"]
|
| 262 |
+
)
|
| 263 |
+
return cls._from_signer_and_info(signer, info, **kwargs)
|
| 264 |
+
|
| 265 |
+
@property
|
| 266 |
+
def service_account_email(self):
|
| 267 |
+
"""The service account email."""
|
| 268 |
+
return self._service_account_email
|
| 269 |
+
|
| 270 |
+
@property
|
| 271 |
+
def project_id(self):
|
| 272 |
+
"""Project ID associated with this credential."""
|
| 273 |
+
return self._project_id
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def requires_scopes(self):
|
| 277 |
+
"""Checks if the credentials requires scopes.
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
bool: True if there are no scopes set otherwise False.
|
| 281 |
+
"""
|
| 282 |
+
return True if not self._scopes else False
|
| 283 |
+
|
| 284 |
+
def _make_copy(self):
|
| 285 |
+
cred = self.__class__(
|
| 286 |
+
self._signer,
|
| 287 |
+
service_account_email=self._service_account_email,
|
| 288 |
+
scopes=copy.copy(self._scopes),
|
| 289 |
+
default_scopes=copy.copy(self._default_scopes),
|
| 290 |
+
token_uri=self._token_uri,
|
| 291 |
+
subject=self._subject,
|
| 292 |
+
project_id=self._project_id,
|
| 293 |
+
quota_project_id=self._quota_project_id,
|
| 294 |
+
additional_claims=self._additional_claims.copy(),
|
| 295 |
+
always_use_jwt_access=self._always_use_jwt_access,
|
| 296 |
+
universe_domain=self._universe_domain,
|
| 297 |
+
)
|
| 298 |
+
cred._cred_file_path = self._cred_file_path
|
| 299 |
+
return cred
|
| 300 |
+
|
| 301 |
+
@_helpers.copy_docstring(credentials.Scoped)
|
| 302 |
+
def with_scopes(self, scopes, default_scopes=None):
|
| 303 |
+
cred = self._make_copy()
|
| 304 |
+
cred._scopes = scopes
|
| 305 |
+
cred._default_scopes = default_scopes
|
| 306 |
+
return cred
|
| 307 |
+
|
| 308 |
+
def with_always_use_jwt_access(self, always_use_jwt_access):
|
| 309 |
+
"""Create a copy of these credentials with the specified always_use_jwt_access value.
|
| 310 |
+
|
| 311 |
+
Args:
|
| 312 |
+
always_use_jwt_access (bool): Whether always use self signed JWT or not.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
google.auth.service_account.Credentials: A new credentials
|
| 316 |
+
instance.
|
| 317 |
+
Raises:
|
| 318 |
+
google.auth.exceptions.InvalidValue: If the universe domain is not
|
| 319 |
+
default and always_use_jwt_access is False.
|
| 320 |
+
"""
|
| 321 |
+
cred = self._make_copy()
|
| 322 |
+
if (
|
| 323 |
+
cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 324 |
+
and not always_use_jwt_access
|
| 325 |
+
):
|
| 326 |
+
raise exceptions.InvalidValue(
|
| 327 |
+
"always_use_jwt_access should be True for non-default universe domain"
|
| 328 |
+
)
|
| 329 |
+
cred._always_use_jwt_access = always_use_jwt_access
|
| 330 |
+
return cred
|
| 331 |
+
|
| 332 |
+
@_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
|
| 333 |
+
def with_universe_domain(self, universe_domain):
|
| 334 |
+
cred = self._make_copy()
|
| 335 |
+
cred._universe_domain = universe_domain
|
| 336 |
+
if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
|
| 337 |
+
cred._always_use_jwt_access = True
|
| 338 |
+
return cred
|
| 339 |
+
|
| 340 |
+
def with_subject(self, subject):
|
| 341 |
+
"""Create a copy of these credentials with the specified subject.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
subject (str): The subject claim.
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
google.auth.service_account.Credentials: A new credentials
|
| 348 |
+
instance.
|
| 349 |
+
"""
|
| 350 |
+
cred = self._make_copy()
|
| 351 |
+
cred._subject = subject
|
| 352 |
+
return cred
|
| 353 |
+
|
| 354 |
+
def with_claims(self, additional_claims):
|
| 355 |
+
"""Returns a copy of these credentials with modified claims.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
additional_claims (Mapping[str, str]): Any additional claims for
|
| 359 |
+
the JWT payload. This will be merged with the current
|
| 360 |
+
additional claims.
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
google.auth.service_account.Credentials: A new credentials
|
| 364 |
+
instance.
|
| 365 |
+
"""
|
| 366 |
+
new_additional_claims = copy.deepcopy(self._additional_claims)
|
| 367 |
+
new_additional_claims.update(additional_claims or {})
|
| 368 |
+
cred = self._make_copy()
|
| 369 |
+
cred._additional_claims = new_additional_claims
|
| 370 |
+
return cred
|
| 371 |
+
|
| 372 |
+
@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
|
| 373 |
+
def with_quota_project(self, quota_project_id):
|
| 374 |
+
cred = self._make_copy()
|
| 375 |
+
cred._quota_project_id = quota_project_id
|
| 376 |
+
return cred
|
| 377 |
+
|
| 378 |
+
@_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
|
| 379 |
+
def with_token_uri(self, token_uri):
|
| 380 |
+
cred = self._make_copy()
|
| 381 |
+
cred._token_uri = token_uri
|
| 382 |
+
return cred
|
| 383 |
+
|
| 384 |
+
def _make_authorization_grant_assertion(self):
|
| 385 |
+
"""Create the OAuth 2.0 assertion.
|
| 386 |
+
|
| 387 |
+
This assertion is used during the OAuth 2.0 grant to acquire an
|
| 388 |
+
access token.
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
bytes: The authorization grant assertion.
|
| 392 |
+
"""
|
| 393 |
+
now = _helpers.utcnow()
|
| 394 |
+
lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
|
| 395 |
+
expiry = now + lifetime
|
| 396 |
+
|
| 397 |
+
payload = {
|
| 398 |
+
"iat": _helpers.datetime_to_secs(now),
|
| 399 |
+
"exp": _helpers.datetime_to_secs(expiry),
|
| 400 |
+
# The issuer must be the service account email.
|
| 401 |
+
"iss": self._service_account_email,
|
| 402 |
+
# The audience must be the auth token endpoint's URI
|
| 403 |
+
"aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
|
| 404 |
+
"scope": _helpers.scopes_to_string(self._scopes or ()),
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
payload.update(self._additional_claims)
|
| 408 |
+
|
| 409 |
+
# The subject can be a user email for domain-wide delegation.
|
| 410 |
+
if self._subject:
|
| 411 |
+
payload.setdefault("sub", self._subject)
|
| 412 |
+
|
| 413 |
+
token = jwt.encode(self._signer, payload)
|
| 414 |
+
|
| 415 |
+
return token
|
| 416 |
+
|
| 417 |
+
def _use_self_signed_jwt(self):
|
| 418 |
+
# Since domain wide delegation doesn't work with self signed JWT. If
|
| 419 |
+
# subject exists, then we should not use self signed JWT.
|
| 420 |
+
return self._subject is None and self._jwt_credentials is not None
|
| 421 |
+
|
| 422 |
+
def _metric_header_for_usage(self):
|
| 423 |
+
if self._use_self_signed_jwt():
|
| 424 |
+
return metrics.CRED_TYPE_SA_JWT
|
| 425 |
+
return metrics.CRED_TYPE_SA_ASSERTION
|
| 426 |
+
|
| 427 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 428 |
+
def refresh(self, request):
|
| 429 |
+
if self._always_use_jwt_access and not self._jwt_credentials:
|
| 430 |
+
# If self signed jwt should be used but jwt credential is not
|
| 431 |
+
# created, try to create one with scopes
|
| 432 |
+
self._create_self_signed_jwt(None)
|
| 433 |
+
|
| 434 |
+
if (
|
| 435 |
+
self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 436 |
+
and self._subject
|
| 437 |
+
):
|
| 438 |
+
raise exceptions.RefreshError(
|
| 439 |
+
"domain wide delegation is not supported for non-default universe domain"
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
if self._use_self_signed_jwt():
|
| 443 |
+
self._jwt_credentials.refresh(request)
|
| 444 |
+
self.token = self._jwt_credentials.token.decode()
|
| 445 |
+
self.expiry = self._jwt_credentials.expiry
|
| 446 |
+
else:
|
| 447 |
+
assertion = self._make_authorization_grant_assertion()
|
| 448 |
+
access_token, expiry, _ = _client.jwt_grant(
|
| 449 |
+
request, self._token_uri, assertion
|
| 450 |
+
)
|
| 451 |
+
self.token = access_token
|
| 452 |
+
self.expiry = expiry
|
| 453 |
+
|
| 454 |
+
def _create_self_signed_jwt(self, audience):
|
| 455 |
+
"""Create a self-signed JWT from the credentials if requirements are met.
|
| 456 |
+
|
| 457 |
+
Args:
|
| 458 |
+
audience (str): The service URL. ``https://[API_ENDPOINT]/``
|
| 459 |
+
"""
|
| 460 |
+
# https://google.aip.dev/auth/4111
|
| 461 |
+
if self._always_use_jwt_access:
|
| 462 |
+
if self._scopes:
|
| 463 |
+
additional_claims = {"scope": " ".join(self._scopes)}
|
| 464 |
+
if (
|
| 465 |
+
self._jwt_credentials is None
|
| 466 |
+
or self._jwt_credentials.additional_claims != additional_claims
|
| 467 |
+
):
|
| 468 |
+
self._jwt_credentials = jwt.Credentials.from_signing_credentials(
|
| 469 |
+
self, None, additional_claims=additional_claims
|
| 470 |
+
)
|
| 471 |
+
elif audience:
|
| 472 |
+
if (
|
| 473 |
+
self._jwt_credentials is None
|
| 474 |
+
or self._jwt_credentials._audience != audience
|
| 475 |
+
):
|
| 476 |
+
|
| 477 |
+
self._jwt_credentials = jwt.Credentials.from_signing_credentials(
|
| 478 |
+
self, audience
|
| 479 |
+
)
|
| 480 |
+
elif self._default_scopes:
|
| 481 |
+
additional_claims = {"scope": " ".join(self._default_scopes)}
|
| 482 |
+
if (
|
| 483 |
+
self._jwt_credentials is None
|
| 484 |
+
or additional_claims != self._jwt_credentials.additional_claims
|
| 485 |
+
):
|
| 486 |
+
self._jwt_credentials = jwt.Credentials.from_signing_credentials(
|
| 487 |
+
self, None, additional_claims=additional_claims
|
| 488 |
+
)
|
| 489 |
+
elif not self._scopes and audience:
|
| 490 |
+
self._jwt_credentials = jwt.Credentials.from_signing_credentials(
|
| 491 |
+
self, audience
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
@_helpers.copy_docstring(credentials.Signing)
|
| 495 |
+
def sign_bytes(self, message):
|
| 496 |
+
return self._signer.sign(message)
|
| 497 |
+
|
| 498 |
+
@property # type: ignore
|
| 499 |
+
@_helpers.copy_docstring(credentials.Signing)
|
| 500 |
+
def signer(self):
|
| 501 |
+
return self._signer
|
| 502 |
+
|
| 503 |
+
@property # type: ignore
|
| 504 |
+
@_helpers.copy_docstring(credentials.Signing)
|
| 505 |
+
def signer_email(self):
|
| 506 |
+
return self._service_account_email
|
| 507 |
+
|
| 508 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 509 |
+
def get_cred_info(self):
|
| 510 |
+
if self._cred_file_path:
|
| 511 |
+
return {
|
| 512 |
+
"credential_source": self._cred_file_path,
|
| 513 |
+
"credential_type": "service account credentials",
|
| 514 |
+
"principal": self.service_account_email,
|
| 515 |
+
}
|
| 516 |
+
return None
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
class IDTokenCredentials(
|
| 520 |
+
credentials.Signing,
|
| 521 |
+
credentials.CredentialsWithQuotaProject,
|
| 522 |
+
credentials.CredentialsWithTokenUri,
|
| 523 |
+
):
|
| 524 |
+
"""Open ID Connect ID Token-based service account credentials.
|
| 525 |
+
|
| 526 |
+
These credentials are largely similar to :class:`.Credentials`, but instead
|
| 527 |
+
of using an OAuth 2.0 Access Token as the bearer token, they use an Open
|
| 528 |
+
ID Connect ID Token as the bearer token. These credentials are useful when
|
| 529 |
+
communicating to services that require ID Tokens and can not accept access
|
| 530 |
+
tokens.
|
| 531 |
+
|
| 532 |
+
Usually, you'll create these credentials with one of the helper
|
| 533 |
+
constructors. To create credentials using a Google service account
|
| 534 |
+
private key JSON file::
|
| 535 |
+
|
| 536 |
+
credentials = (
|
| 537 |
+
service_account.IDTokenCredentials.from_service_account_file(
|
| 538 |
+
'service-account.json'))
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
Or if you already have the service account file loaded::
|
| 542 |
+
|
| 543 |
+
service_account_info = json.load(open('service_account.json'))
|
| 544 |
+
credentials = (
|
| 545 |
+
service_account.IDTokenCredentials.from_service_account_info(
|
| 546 |
+
service_account_info))
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
Both helper methods pass on arguments to the constructor, so you can
|
| 550 |
+
specify additional scopes and a subject if necessary::
|
| 551 |
+
|
| 552 |
+
credentials = (
|
| 553 |
+
service_account.IDTokenCredentials.from_service_account_file(
|
| 554 |
+
'service-account.json',
|
| 555 |
+
scopes=['email'],
|
| 556 |
+
subject='user@example.com'))
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
The credentials are considered immutable. If you want to modify the scopes
|
| 560 |
+
or the subject used for delegation, use :meth:`with_scopes` or
|
| 561 |
+
:meth:`with_subject`::
|
| 562 |
+
|
| 563 |
+
scoped_credentials = credentials.with_scopes(['email'])
|
| 564 |
+
delegated_credentials = credentials.with_subject(subject)
|
| 565 |
+
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
def __init__(
|
| 569 |
+
self,
|
| 570 |
+
signer,
|
| 571 |
+
service_account_email,
|
| 572 |
+
token_uri,
|
| 573 |
+
target_audience,
|
| 574 |
+
additional_claims=None,
|
| 575 |
+
quota_project_id=None,
|
| 576 |
+
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
|
| 577 |
+
):
|
| 578 |
+
"""
|
| 579 |
+
Args:
|
| 580 |
+
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
|
| 581 |
+
service_account_email (str): The service account's email.
|
| 582 |
+
token_uri (str): The OAuth 2.0 Token URI.
|
| 583 |
+
target_audience (str): The intended audience for these credentials,
|
| 584 |
+
used when requesting the ID Token. The ID Token's ``aud`` claim
|
| 585 |
+
will be set to this string.
|
| 586 |
+
additional_claims (Mapping[str, str]): Any additional claims for
|
| 587 |
+
the JWT assertion used in the authorization grant.
|
| 588 |
+
quota_project_id (Optional[str]): The project ID used for quota and billing.
|
| 589 |
+
universe_domain (str): The universe domain. The default
|
| 590 |
+
universe domain is googleapis.com. For default value IAM ID
|
| 591 |
+
token endponint is used for token refresh. Note that
|
| 592 |
+
iam.serviceAccountTokenCreator role is required to use the IAM
|
| 593 |
+
endpoint.
|
| 594 |
+
.. note:: Typically one of the helper constructors
|
| 595 |
+
:meth:`from_service_account_file` or
|
| 596 |
+
:meth:`from_service_account_info` are used instead of calling the
|
| 597 |
+
constructor directly.
|
| 598 |
+
"""
|
| 599 |
+
super(IDTokenCredentials, self).__init__()
|
| 600 |
+
self._signer = signer
|
| 601 |
+
self._service_account_email = service_account_email
|
| 602 |
+
self._token_uri = token_uri
|
| 603 |
+
self._target_audience = target_audience
|
| 604 |
+
self._quota_project_id = quota_project_id
|
| 605 |
+
self._use_iam_endpoint = False
|
| 606 |
+
|
| 607 |
+
if not universe_domain:
|
| 608 |
+
self._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 609 |
+
else:
|
| 610 |
+
self._universe_domain = universe_domain
|
| 611 |
+
self._iam_id_token_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace(
|
| 612 |
+
"googleapis.com", self._universe_domain
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
|
| 616 |
+
self._use_iam_endpoint = True
|
| 617 |
+
|
| 618 |
+
if additional_claims is not None:
|
| 619 |
+
self._additional_claims = additional_claims
|
| 620 |
+
else:
|
| 621 |
+
self._additional_claims = {}
|
| 622 |
+
|
| 623 |
+
@classmethod
|
| 624 |
+
def _from_signer_and_info(cls, signer, info, **kwargs):
|
| 625 |
+
"""Creates a credentials instance from a signer and service account
|
| 626 |
+
info.
|
| 627 |
+
|
| 628 |
+
Args:
|
| 629 |
+
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
|
| 630 |
+
info (Mapping[str, str]): The service account info.
|
| 631 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 632 |
+
|
| 633 |
+
Returns:
|
| 634 |
+
google.auth.jwt.IDTokenCredentials: The constructed credentials.
|
| 635 |
+
|
| 636 |
+
Raises:
|
| 637 |
+
ValueError: If the info is not in the expected format.
|
| 638 |
+
"""
|
| 639 |
+
kwargs.setdefault("service_account_email", info["client_email"])
|
| 640 |
+
kwargs.setdefault("token_uri", info["token_uri"])
|
| 641 |
+
if "universe_domain" in info:
|
| 642 |
+
kwargs["universe_domain"] = info["universe_domain"]
|
| 643 |
+
return cls(signer, **kwargs)
|
| 644 |
+
|
| 645 |
+
@classmethod
|
| 646 |
+
def from_service_account_info(cls, info, **kwargs):
|
| 647 |
+
"""Creates a credentials instance from parsed service account info.
|
| 648 |
+
|
| 649 |
+
Args:
|
| 650 |
+
info (Mapping[str, str]): The service account info in Google
|
| 651 |
+
format.
|
| 652 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 653 |
+
|
| 654 |
+
Returns:
|
| 655 |
+
google.auth.service_account.IDTokenCredentials: The constructed
|
| 656 |
+
credentials.
|
| 657 |
+
|
| 658 |
+
Raises:
|
| 659 |
+
ValueError: If the info is not in the expected format.
|
| 660 |
+
"""
|
| 661 |
+
signer = _service_account_info.from_dict(
|
| 662 |
+
info, require=["client_email", "token_uri"]
|
| 663 |
+
)
|
| 664 |
+
return cls._from_signer_and_info(signer, info, **kwargs)
|
| 665 |
+
|
| 666 |
+
@classmethod
|
| 667 |
+
def from_service_account_file(cls, filename, **kwargs):
|
| 668 |
+
"""Creates a credentials instance from a service account json file.
|
| 669 |
+
|
| 670 |
+
Args:
|
| 671 |
+
filename (str): The path to the service account json file.
|
| 672 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 673 |
+
|
| 674 |
+
Returns:
|
| 675 |
+
google.auth.service_account.IDTokenCredentials: The constructed
|
| 676 |
+
credentials.
|
| 677 |
+
"""
|
| 678 |
+
info, signer = _service_account_info.from_filename(
|
| 679 |
+
filename, require=["client_email", "token_uri"]
|
| 680 |
+
)
|
| 681 |
+
return cls._from_signer_and_info(signer, info, **kwargs)
|
| 682 |
+
|
| 683 |
+
def _make_copy(self):
|
| 684 |
+
cred = self.__class__(
|
| 685 |
+
self._signer,
|
| 686 |
+
service_account_email=self._service_account_email,
|
| 687 |
+
token_uri=self._token_uri,
|
| 688 |
+
target_audience=self._target_audience,
|
| 689 |
+
additional_claims=self._additional_claims.copy(),
|
| 690 |
+
quota_project_id=self.quota_project_id,
|
| 691 |
+
universe_domain=self._universe_domain,
|
| 692 |
+
)
|
| 693 |
+
# _use_iam_endpoint is not exposed in the constructor
|
| 694 |
+
cred._use_iam_endpoint = self._use_iam_endpoint
|
| 695 |
+
return cred
|
| 696 |
+
|
| 697 |
+
def with_target_audience(self, target_audience):
|
| 698 |
+
"""Create a copy of these credentials with the specified target
|
| 699 |
+
audience.
|
| 700 |
+
|
| 701 |
+
Args:
|
| 702 |
+
target_audience (str): The intended audience for these credentials,
|
| 703 |
+
used when requesting the ID Token.
|
| 704 |
+
|
| 705 |
+
Returns:
|
| 706 |
+
google.auth.service_account.IDTokenCredentials: A new credentials
|
| 707 |
+
instance.
|
| 708 |
+
"""
|
| 709 |
+
cred = self._make_copy()
|
| 710 |
+
cred._target_audience = target_audience
|
| 711 |
+
return cred
|
| 712 |
+
|
| 713 |
+
def _with_use_iam_endpoint(self, use_iam_endpoint):
|
| 714 |
+
"""Create a copy of these credentials with the use_iam_endpoint value.
|
| 715 |
+
|
| 716 |
+
Args:
|
| 717 |
+
use_iam_endpoint (bool): If True, IAM generateIdToken endpoint will
|
| 718 |
+
be used instead of the token_uri. Note that
|
| 719 |
+
iam.serviceAccountTokenCreator role is required to use the IAM
|
| 720 |
+
endpoint. The default value is False. This feature is currently
|
| 721 |
+
experimental and subject to change without notice.
|
| 722 |
+
|
| 723 |
+
Returns:
|
| 724 |
+
google.auth.service_account.IDTokenCredentials: A new credentials
|
| 725 |
+
instance.
|
| 726 |
+
Raises:
|
| 727 |
+
google.auth.exceptions.InvalidValue: If the universe domain is not
|
| 728 |
+
default and use_iam_endpoint is False.
|
| 729 |
+
"""
|
| 730 |
+
cred = self._make_copy()
|
| 731 |
+
if (
|
| 732 |
+
cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN
|
| 733 |
+
and not use_iam_endpoint
|
| 734 |
+
):
|
| 735 |
+
raise exceptions.InvalidValue(
|
| 736 |
+
"use_iam_endpoint should be True for non-default universe domain"
|
| 737 |
+
)
|
| 738 |
+
cred._use_iam_endpoint = use_iam_endpoint
|
| 739 |
+
return cred
|
| 740 |
+
|
| 741 |
+
@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
|
| 742 |
+
def with_quota_project(self, quota_project_id):
|
| 743 |
+
cred = self._make_copy()
|
| 744 |
+
cred._quota_project_id = quota_project_id
|
| 745 |
+
return cred
|
| 746 |
+
|
| 747 |
+
@_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
|
| 748 |
+
def with_token_uri(self, token_uri):
|
| 749 |
+
cred = self._make_copy()
|
| 750 |
+
cred._token_uri = token_uri
|
| 751 |
+
return cred
|
| 752 |
+
|
| 753 |
+
def _make_authorization_grant_assertion(self):
|
| 754 |
+
"""Create the OAuth 2.0 assertion.
|
| 755 |
+
|
| 756 |
+
This assertion is used during the OAuth 2.0 grant to acquire an
|
| 757 |
+
ID token.
|
| 758 |
+
|
| 759 |
+
Returns:
|
| 760 |
+
bytes: The authorization grant assertion.
|
| 761 |
+
"""
|
| 762 |
+
now = _helpers.utcnow()
|
| 763 |
+
lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
|
| 764 |
+
expiry = now + lifetime
|
| 765 |
+
|
| 766 |
+
payload = {
|
| 767 |
+
"iat": _helpers.datetime_to_secs(now),
|
| 768 |
+
"exp": _helpers.datetime_to_secs(expiry),
|
| 769 |
+
# The issuer must be the service account email.
|
| 770 |
+
"iss": self.service_account_email,
|
| 771 |
+
# The audience must be the auth token endpoint's URI
|
| 772 |
+
"aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
|
| 773 |
+
# The target audience specifies which service the ID token is
|
| 774 |
+
# intended for.
|
| 775 |
+
"target_audience": self._target_audience,
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
payload.update(self._additional_claims)
|
| 779 |
+
|
| 780 |
+
token = jwt.encode(self._signer, payload)
|
| 781 |
+
|
| 782 |
+
return token
|
| 783 |
+
|
| 784 |
+
def _refresh_with_iam_endpoint(self, request):
|
| 785 |
+
"""Use IAM generateIdToken endpoint to obtain an ID token.
|
| 786 |
+
|
| 787 |
+
It works as follows:
|
| 788 |
+
|
| 789 |
+
1. First we create a self signed jwt with
|
| 790 |
+
https://www.googleapis.com/auth/iam being the scope.
|
| 791 |
+
|
| 792 |
+
2. Next we use the self signed jwt as the access token, and make a POST
|
| 793 |
+
request to IAM generateIdToken endpoint. The request body is:
|
| 794 |
+
{
|
| 795 |
+
"audience": self._target_audience,
|
| 796 |
+
"includeEmail": "true",
|
| 797 |
+
"useEmailAzp": "true",
|
| 798 |
+
}
|
| 799 |
+
|
| 800 |
+
If the request is succesfully, it will return {"token":"the ID token"},
|
| 801 |
+
and we can extract the ID token and compute its expiry.
|
| 802 |
+
"""
|
| 803 |
+
jwt_credentials = jwt.Credentials.from_signing_credentials(
|
| 804 |
+
self,
|
| 805 |
+
None,
|
| 806 |
+
additional_claims={"scope": "https://www.googleapis.com/auth/iam"},
|
| 807 |
+
)
|
| 808 |
+
jwt_credentials.refresh(request)
|
| 809 |
+
self.token, self.expiry = _client.call_iam_generate_id_token_endpoint(
|
| 810 |
+
request,
|
| 811 |
+
self._iam_id_token_endpoint,
|
| 812 |
+
self.signer_email,
|
| 813 |
+
self._target_audience,
|
| 814 |
+
jwt_credentials.token.decode(),
|
| 815 |
+
self._universe_domain,
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
@_helpers.copy_docstring(credentials.Credentials)
|
| 819 |
+
def refresh(self, request):
|
| 820 |
+
if self._use_iam_endpoint:
|
| 821 |
+
self._refresh_with_iam_endpoint(request)
|
| 822 |
+
else:
|
| 823 |
+
assertion = self._make_authorization_grant_assertion()
|
| 824 |
+
access_token, expiry, _ = _client.id_token_jwt_grant(
|
| 825 |
+
request, self._token_uri, assertion
|
| 826 |
+
)
|
| 827 |
+
self.token = access_token
|
| 828 |
+
self.expiry = expiry
|
| 829 |
+
|
| 830 |
+
@property
|
| 831 |
+
def service_account_email(self):
|
| 832 |
+
"""The service account email."""
|
| 833 |
+
return self._service_account_email
|
| 834 |
+
|
| 835 |
+
@_helpers.copy_docstring(credentials.Signing)
|
| 836 |
+
def sign_bytes(self, message):
|
| 837 |
+
return self._signer.sign(message)
|
| 838 |
+
|
| 839 |
+
@property # type: ignore
|
| 840 |
+
@_helpers.copy_docstring(credentials.Signing)
|
| 841 |
+
def signer(self):
|
| 842 |
+
return self._signer
|
| 843 |
+
|
| 844 |
+
@property # type: ignore
|
| 845 |
+
@_helpers.copy_docstring(credentials.Signing)
|
| 846 |
+
def signer_email(self):
|
| 847 |
+
return self._service_account_email
|
lib/python3.10/site-packages/google/oauth2/utils.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 |
+
"""OAuth 2.0 Utilities.
|
| 16 |
+
|
| 17 |
+
This module provides implementations for various OAuth 2.0 utilities.
|
| 18 |
+
This includes `OAuth error handling`_ and
|
| 19 |
+
`Client authentication for OAuth flows`_.
|
| 20 |
+
|
| 21 |
+
OAuth error handling
|
| 22 |
+
--------------------
|
| 23 |
+
This will define interfaces for handling OAuth related error responses as
|
| 24 |
+
stated in `RFC 6749 section 5.2`_.
|
| 25 |
+
This will include a common function to convert these HTTP error responses to a
|
| 26 |
+
:class:`google.auth.exceptions.OAuthError` exception.
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
Client authentication for OAuth flows
|
| 30 |
+
-------------------------------------
|
| 31 |
+
We introduce an interface for defining client authentication credentials based
|
| 32 |
+
on `RFC 6749 section 2.3.1`_. This will expose the following
|
| 33 |
+
capabilities:
|
| 34 |
+
|
| 35 |
+
* Ability to support basic authentication via request header.
|
| 36 |
+
* Ability to support bearer token authentication via request header.
|
| 37 |
+
* Ability to support client ID / secret authentication via request body.
|
| 38 |
+
|
| 39 |
+
.. _RFC 6749 section 2.3.1: https://tools.ietf.org/html/rfc6749#section-2.3.1
|
| 40 |
+
.. _RFC 6749 section 5.2: https://tools.ietf.org/html/rfc6749#section-5.2
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
import abc
|
| 44 |
+
import base64
|
| 45 |
+
import enum
|
| 46 |
+
import json
|
| 47 |
+
|
| 48 |
+
from google.auth import exceptions
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# OAuth client authentication based on
|
| 52 |
+
# https://tools.ietf.org/html/rfc6749#section-2.3.
|
| 53 |
+
class ClientAuthType(enum.Enum):
|
| 54 |
+
basic = 1
|
| 55 |
+
request_body = 2
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ClientAuthentication(object):
|
| 59 |
+
"""Defines the client authentication credentials for basic and request-body
|
| 60 |
+
types based on https://tools.ietf.org/html/rfc6749#section-2.3.1.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, client_auth_type, client_id, client_secret=None):
|
| 64 |
+
"""Instantiates a client authentication object containing the client ID
|
| 65 |
+
and secret credentials for basic and response-body auth.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
client_auth_type (google.oauth2.oauth_utils.ClientAuthType): The
|
| 69 |
+
client authentication type.
|
| 70 |
+
client_id (str): The client ID.
|
| 71 |
+
client_secret (Optional[str]): The client secret.
|
| 72 |
+
"""
|
| 73 |
+
self.client_auth_type = client_auth_type
|
| 74 |
+
self.client_id = client_id
|
| 75 |
+
self.client_secret = client_secret
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class OAuthClientAuthHandler(metaclass=abc.ABCMeta):
|
| 79 |
+
"""Abstract class for handling client authentication in OAuth-based
|
| 80 |
+
operations.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, client_authentication=None):
|
| 84 |
+
"""Instantiates an OAuth client authentication handler.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
client_authentication (Optional[google.oauth2.utils.ClientAuthentication]):
|
| 88 |
+
The OAuth client authentication credentials if available.
|
| 89 |
+
"""
|
| 90 |
+
super(OAuthClientAuthHandler, self).__init__()
|
| 91 |
+
self._client_authentication = client_authentication
|
| 92 |
+
|
| 93 |
+
def apply_client_authentication_options(
|
| 94 |
+
self, headers, request_body=None, bearer_token=None
|
| 95 |
+
):
|
| 96 |
+
"""Applies client authentication on the OAuth request's headers or POST
|
| 97 |
+
body.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
headers (Mapping[str, str]): The HTTP request header.
|
| 101 |
+
request_body (Optional[Mapping[str, str]]): The HTTP request body
|
| 102 |
+
dictionary. For requests that do not support request body, this
|
| 103 |
+
is None and will be ignored.
|
| 104 |
+
bearer_token (Optional[str]): The optional bearer token.
|
| 105 |
+
"""
|
| 106 |
+
# Inject authenticated header.
|
| 107 |
+
self._inject_authenticated_headers(headers, bearer_token)
|
| 108 |
+
# Inject authenticated request body.
|
| 109 |
+
if bearer_token is None:
|
| 110 |
+
self._inject_authenticated_request_body(request_body)
|
| 111 |
+
|
| 112 |
+
def _inject_authenticated_headers(self, headers, bearer_token=None):
|
| 113 |
+
if bearer_token is not None:
|
| 114 |
+
headers["Authorization"] = "Bearer %s" % bearer_token
|
| 115 |
+
elif (
|
| 116 |
+
self._client_authentication is not None
|
| 117 |
+
and self._client_authentication.client_auth_type is ClientAuthType.basic
|
| 118 |
+
):
|
| 119 |
+
username = self._client_authentication.client_id
|
| 120 |
+
password = self._client_authentication.client_secret or ""
|
| 121 |
+
|
| 122 |
+
credentials = base64.b64encode(
|
| 123 |
+
("%s:%s" % (username, password)).encode()
|
| 124 |
+
).decode()
|
| 125 |
+
headers["Authorization"] = "Basic %s" % credentials
|
| 126 |
+
|
| 127 |
+
def _inject_authenticated_request_body(self, request_body):
|
| 128 |
+
if (
|
| 129 |
+
self._client_authentication is not None
|
| 130 |
+
and self._client_authentication.client_auth_type
|
| 131 |
+
is ClientAuthType.request_body
|
| 132 |
+
):
|
| 133 |
+
if request_body is None:
|
| 134 |
+
raise exceptions.OAuthError(
|
| 135 |
+
"HTTP request does not support request-body"
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
request_body["client_id"] = self._client_authentication.client_id
|
| 139 |
+
request_body["client_secret"] = (
|
| 140 |
+
self._client_authentication.client_secret or ""
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def handle_error_response(response_body):
|
| 145 |
+
"""Translates an error response from an OAuth operation into an
|
| 146 |
+
OAuthError exception.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
response_body (str): The decoded response data.
|
| 150 |
+
|
| 151 |
+
Raises:
|
| 152 |
+
google.auth.exceptions.OAuthError
|
| 153 |
+
"""
|
| 154 |
+
try:
|
| 155 |
+
error_components = []
|
| 156 |
+
error_data = json.loads(response_body)
|
| 157 |
+
|
| 158 |
+
error_components.append("Error code {}".format(error_data["error"]))
|
| 159 |
+
if "error_description" in error_data:
|
| 160 |
+
error_components.append(": {}".format(error_data["error_description"]))
|
| 161 |
+
if "error_uri" in error_data:
|
| 162 |
+
error_components.append(" - {}".format(error_data["error_uri"]))
|
| 163 |
+
error_details = "".join(error_components)
|
| 164 |
+
# If no details could be extracted, use the response data.
|
| 165 |
+
except (KeyError, ValueError):
|
| 166 |
+
error_details = response_body
|
| 167 |
+
|
| 168 |
+
raise exceptions.OAuthError(error_details, response_body)
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/LICENSE.markdown-it
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person
|
| 4 |
+
obtaining a copy of this software and associated documentation
|
| 5 |
+
files (the "Software"), to deal in the Software without
|
| 6 |
+
restriction, including without limitation the rights to use,
|
| 7 |
+
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 8 |
+
copies of the Software, and to permit persons to whom the
|
| 9 |
+
Software is furnished to do so, subject to the following
|
| 10 |
+
conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be
|
| 13 |
+
included in all copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 16 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
| 17 |
+
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 18 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
| 19 |
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
| 20 |
+
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 21 |
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
| 22 |
+
OTHER DEALINGS IN THE SOFTWARE.
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: markdown-it-py
|
| 3 |
+
Version: 3.0.0
|
| 4 |
+
Summary: Python port of markdown-it. Markdown parsing, done right!
|
| 5 |
+
Keywords: markdown,lexer,parser,commonmark,markdown-it
|
| 6 |
+
Author-email: Chris Sewell <chrisj_sewell@hotmail.com>
|
| 7 |
+
Requires-Python: >=3.8
|
| 8 |
+
Description-Content-Type: text/markdown
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 12 |
+
Classifier: Programming Language :: Python :: 3
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 17 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 18 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 19 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 20 |
+
Classifier: Topic :: Text Processing :: Markup
|
| 21 |
+
Requires-Dist: mdurl~=0.1
|
| 22 |
+
Requires-Dist: psutil ; extra == "benchmarking"
|
| 23 |
+
Requires-Dist: pytest ; extra == "benchmarking"
|
| 24 |
+
Requires-Dist: pytest-benchmark ; extra == "benchmarking"
|
| 25 |
+
Requires-Dist: pre-commit~=3.0 ; extra == "code_style"
|
| 26 |
+
Requires-Dist: commonmark~=0.9 ; extra == "compare"
|
| 27 |
+
Requires-Dist: markdown~=3.4 ; extra == "compare"
|
| 28 |
+
Requires-Dist: mistletoe~=1.0 ; extra == "compare"
|
| 29 |
+
Requires-Dist: mistune~=2.0 ; extra == "compare"
|
| 30 |
+
Requires-Dist: panflute~=2.3 ; extra == "compare"
|
| 31 |
+
Requires-Dist: linkify-it-py>=1,<3 ; extra == "linkify"
|
| 32 |
+
Requires-Dist: mdit-py-plugins ; extra == "plugins"
|
| 33 |
+
Requires-Dist: gprof2dot ; extra == "profiling"
|
| 34 |
+
Requires-Dist: mdit-py-plugins ; extra == "rtd"
|
| 35 |
+
Requires-Dist: myst-parser ; extra == "rtd"
|
| 36 |
+
Requires-Dist: pyyaml ; extra == "rtd"
|
| 37 |
+
Requires-Dist: sphinx ; extra == "rtd"
|
| 38 |
+
Requires-Dist: sphinx-copybutton ; extra == "rtd"
|
| 39 |
+
Requires-Dist: sphinx-design ; extra == "rtd"
|
| 40 |
+
Requires-Dist: sphinx_book_theme ; extra == "rtd"
|
| 41 |
+
Requires-Dist: jupyter_sphinx ; extra == "rtd"
|
| 42 |
+
Requires-Dist: coverage ; extra == "testing"
|
| 43 |
+
Requires-Dist: pytest ; extra == "testing"
|
| 44 |
+
Requires-Dist: pytest-cov ; extra == "testing"
|
| 45 |
+
Requires-Dist: pytest-regressions ; extra == "testing"
|
| 46 |
+
Project-URL: Documentation, https://markdown-it-py.readthedocs.io
|
| 47 |
+
Project-URL: Homepage, https://github.com/executablebooks/markdown-it-py
|
| 48 |
+
Provides-Extra: benchmarking
|
| 49 |
+
Provides-Extra: code_style
|
| 50 |
+
Provides-Extra: compare
|
| 51 |
+
Provides-Extra: linkify
|
| 52 |
+
Provides-Extra: plugins
|
| 53 |
+
Provides-Extra: profiling
|
| 54 |
+
Provides-Extra: rtd
|
| 55 |
+
Provides-Extra: testing
|
| 56 |
+
|
| 57 |
+
# markdown-it-py
|
| 58 |
+
|
| 59 |
+
[![Github-CI][github-ci]][github-link]
|
| 60 |
+
[![Coverage Status][codecov-badge]][codecov-link]
|
| 61 |
+
[![PyPI][pypi-badge]][pypi-link]
|
| 62 |
+
[![Conda][conda-badge]][conda-link]
|
| 63 |
+
[![Code style: black][black-badge]][black-link]
|
| 64 |
+
[![PyPI - Downloads][install-badge]][install-link]
|
| 65 |
+
|
| 66 |
+
> Markdown parser done right.
|
| 67 |
+
|
| 68 |
+
- Follows the __[CommonMark spec](http://spec.commonmark.org/)__ for baseline parsing
|
| 69 |
+
- Configurable syntax: you can add new rules and even replace existing ones.
|
| 70 |
+
- Pluggable: Adds syntax extensions to extend the parser (see the [plugin list][md-plugins]).
|
| 71 |
+
- High speed (see our [benchmarking tests][md-performance])
|
| 72 |
+
- [Safe by default][md-security]
|
| 73 |
+
- Member of [Google's Assured Open Source Software](https://cloud.google.com/assured-open-source-software/docs/supported-packages)
|
| 74 |
+
|
| 75 |
+
This is a Python port of [markdown-it], and some of its associated plugins.
|
| 76 |
+
For more details see: <https://markdown-it-py.readthedocs.io>.
|
| 77 |
+
|
| 78 |
+
For details on [markdown-it] itself, see:
|
| 79 |
+
|
| 80 |
+
- The __[Live demo](https://markdown-it.github.io)__
|
| 81 |
+
- [The markdown-it README][markdown-it-readme]
|
| 82 |
+
|
| 83 |
+
## Installation
|
| 84 |
+
|
| 85 |
+
```bash
|
| 86 |
+
conda install -c conda-forge markdown-it-py
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
or
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
pip install markdown-it-py[plugins]
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
or with extras
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
conda install -c conda-forge markdown-it-py linkify-it-py mdit-py-plugins
|
| 99 |
+
pip install markdown-it-py[linkify,plugins]
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
## Usage
|
| 103 |
+
|
| 104 |
+
### Python API Usage
|
| 105 |
+
|
| 106 |
+
Render markdown to HTML with markdown-it-py and a custom configuration
|
| 107 |
+
with and without plugins and features:
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
from markdown_it import MarkdownIt
|
| 111 |
+
from mdit_py_plugins.front_matter import front_matter_plugin
|
| 112 |
+
from mdit_py_plugins.footnote import footnote_plugin
|
| 113 |
+
|
| 114 |
+
md = (
|
| 115 |
+
MarkdownIt('commonmark' ,{'breaks':True,'html':True})
|
| 116 |
+
.use(front_matter_plugin)
|
| 117 |
+
.use(footnote_plugin)
|
| 118 |
+
.enable('table')
|
| 119 |
+
)
|
| 120 |
+
text = ("""
|
| 121 |
+
---
|
| 122 |
+
a: 1
|
| 123 |
+
---
|
| 124 |
+
|
| 125 |
+
a | b
|
| 126 |
+
- | -
|
| 127 |
+
1 | 2
|
| 128 |
+
|
| 129 |
+
A footnote [^1]
|
| 130 |
+
|
| 131 |
+
[^1]: some details
|
| 132 |
+
""")
|
| 133 |
+
tokens = md.parse(text)
|
| 134 |
+
html_text = md.render(text)
|
| 135 |
+
|
| 136 |
+
## To export the html to a file, uncomment the lines below:
|
| 137 |
+
# from pathlib import Path
|
| 138 |
+
# Path("output.html").write_text(html_text)
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
### Command-line Usage
|
| 142 |
+
|
| 143 |
+
Render markdown to HTML with markdown-it-py from the
|
| 144 |
+
command-line:
|
| 145 |
+
|
| 146 |
+
```console
|
| 147 |
+
usage: markdown-it [-h] [-v] [filenames [filenames ...]]
|
| 148 |
+
|
| 149 |
+
Parse one or more markdown files, convert each to HTML, and print to stdout
|
| 150 |
+
|
| 151 |
+
positional arguments:
|
| 152 |
+
filenames specify an optional list of files to convert
|
| 153 |
+
|
| 154 |
+
optional arguments:
|
| 155 |
+
-h, --help show this help message and exit
|
| 156 |
+
-v, --version show program's version number and exit
|
| 157 |
+
|
| 158 |
+
Interactive:
|
| 159 |
+
|
| 160 |
+
$ markdown-it
|
| 161 |
+
markdown-it-py [version 0.0.0] (interactive)
|
| 162 |
+
Type Ctrl-D to complete input, or Ctrl-C to exit.
|
| 163 |
+
>>> # Example
|
| 164 |
+
... > markdown *input*
|
| 165 |
+
...
|
| 166 |
+
<h1>Example</h1>
|
| 167 |
+
<blockquote>
|
| 168 |
+
<p>markdown <em>input</em></p>
|
| 169 |
+
</blockquote>
|
| 170 |
+
|
| 171 |
+
Batch:
|
| 172 |
+
|
| 173 |
+
$ markdown-it README.md README.footer.md > index.html
|
| 174 |
+
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
## References / Thanks
|
| 178 |
+
|
| 179 |
+
Big thanks to the authors of [markdown-it]:
|
| 180 |
+
|
| 181 |
+
- Alex Kocharin [github/rlidwka](https://github.com/rlidwka)
|
| 182 |
+
- Vitaly Puzrin [github/puzrin](https://github.com/puzrin)
|
| 183 |
+
|
| 184 |
+
Also [John MacFarlane](https://github.com/jgm) for his work on the CommonMark spec and reference implementations.
|
| 185 |
+
|
| 186 |
+
[github-ci]: https://github.com/executablebooks/markdown-it-py/workflows/Python%20package/badge.svg?branch=master
|
| 187 |
+
[github-link]: https://github.com/executablebooks/markdown-it-py
|
| 188 |
+
[pypi-badge]: https://img.shields.io/pypi/v/markdown-it-py.svg
|
| 189 |
+
[pypi-link]: https://pypi.org/project/markdown-it-py
|
| 190 |
+
[conda-badge]: https://anaconda.org/conda-forge/markdown-it-py/badges/version.svg
|
| 191 |
+
[conda-link]: https://anaconda.org/conda-forge/markdown-it-py
|
| 192 |
+
[codecov-badge]: https://codecov.io/gh/executablebooks/markdown-it-py/branch/master/graph/badge.svg
|
| 193 |
+
[codecov-link]: https://codecov.io/gh/executablebooks/markdown-it-py
|
| 194 |
+
[black-badge]: https://img.shields.io/badge/code%20style-black-000000.svg
|
| 195 |
+
[black-link]: https://github.com/ambv/black
|
| 196 |
+
[install-badge]: https://img.shields.io/pypi/dw/markdown-it-py?label=pypi%20installs
|
| 197 |
+
[install-link]: https://pypistats.org/packages/markdown-it-py
|
| 198 |
+
|
| 199 |
+
[CommonMark spec]: http://spec.commonmark.org/
|
| 200 |
+
[markdown-it]: https://github.com/markdown-it/markdown-it
|
| 201 |
+
[markdown-it-readme]: https://github.com/markdown-it/markdown-it/blob/master/README.md
|
| 202 |
+
[md-security]: https://markdown-it-py.readthedocs.io/en/latest/other.html
|
| 203 |
+
[md-performance]: https://markdown-it-py.readthedocs.io/en/latest/other.html
|
| 204 |
+
[md-plugins]: https://markdown-it-py.readthedocs.io/en/latest/plugins.html
|
| 205 |
+
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
../../../bin/markdown-it,sha256=rippJ0Ff_iQ1MyEKEl-7lfazh8qKaVlxlRULryUreh0,332
|
| 2 |
+
markdown_it/__init__.py,sha256=9v3vCD7XQJujcZLU2F14T8O88JJO93rZaUoKu7cocH8,113
|
| 3 |
+
markdown_it/_compat.py,sha256=mfhalPobHpl8uYt2V6SCOZq3HqaGlWP8MjICwDvS_xE,246
|
| 4 |
+
markdown_it/_punycode.py,sha256=Y_m-fzc5Ey_Kw09MPNN5TUMnPXm2cACUZE_qwUkfFrM,2364
|
| 5 |
+
markdown_it/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
markdown_it/cli/parse.py,sha256=ZiTSx6t7nLk7rGAtIi0a02EB9sDGJn7YLjKKtufdwNA,2901
|
| 7 |
+
markdown_it/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 8 |
+
markdown_it/common/entities.py,sha256=6ulEjBAWYH5lVobgpn5lChPYhPKkdPyVHpNT7O1_x90,156
|
| 9 |
+
markdown_it/common/html_blocks.py,sha256=1cMBp6jIdXqCHvEs2mpJqVGqTuFi6ExL4VO754yksgU,932
|
| 10 |
+
markdown_it/common/html_re.py,sha256=0q5QFkSnX_l7Ob37MDSj2UYT0onCPz_07hUod2K-a6A,929
|
| 11 |
+
markdown_it/common/normalize_url.py,sha256=avOXnLd9xw5jU1q5PLftjAM9pvGx8l9QDEkmZSyrMgg,2568
|
| 12 |
+
markdown_it/common/utils.py,sha256=l2ypUup7jVBwGZJb8M2lxllmTWq8wN5TMV40Mndqu1A,10728
|
| 13 |
+
markdown_it/helpers/__init__.py,sha256=9W7GycpZcq2up1CdVcUpdN77i9Vl4N0CT3y3qMkTjY4,253
|
| 14 |
+
markdown_it/helpers/parse_link_destination.py,sha256=whJoEo42RmgiVpyc2TmTb73nPK3L-DZuZqfE2f8B20Q,1977
|
| 15 |
+
markdown_it/helpers/parse_link_label.py,sha256=HXAnGlAL-2Op6I-lfeuzBIJBjESCRZws6xKKS3lKFSg,1036
|
| 16 |
+
markdown_it/helpers/parse_link_title.py,sha256=5h5YctAUPmaeBqAlCDzzB220-i64HxYyJ27ui-xMBn0,1425
|
| 17 |
+
markdown_it/main.py,sha256=7BYAkBbDmgbdVGNrpAaWZ_-u2-DoYsOCtXWg5uv3Gvg,12772
|
| 18 |
+
markdown_it/parser_block.py,sha256=1bvZMDIdfBYrRNHpZPzmX6W4GXXaFUDqq2iaxDWP-BM,3911
|
| 19 |
+
markdown_it/parser_core.py,sha256=asPHnvL0sk2oqWC69VM8OAqKs-Dk--GRHhGwZonLm6s,1010
|
| 20 |
+
markdown_it/parser_inline.py,sha256=0ZAiRx2GkQ35va1QRxDeDZvpa44wZBNnVFsGzCyj_Po,4997
|
| 21 |
+
markdown_it/port.yaml,sha256=F6WvtDFxjuZ5o0NtmJO0P8SkG6OfONCj_ggKgx4iYWU,2446
|
| 22 |
+
markdown_it/presets/__init__.py,sha256=tLc9od5iXBEkKR6wbXOVPC5S5vkGYK-67tQslhWu7LY,970
|
| 23 |
+
markdown_it/presets/commonmark.py,sha256=pqVnOnMmCmiZWHvNnXx4E1FS8VV07jcqUW1EsHuv9rE,2868
|
| 24 |
+
markdown_it/presets/default.py,sha256=TgqnjjHX6SWcElk5yjW1hoP8t2-ESZ0QyrmHprmIL18,1810
|
| 25 |
+
markdown_it/presets/zero.py,sha256=2vETQRRW1v9Ug3TsdRhM9r6wgZRuTcvojwcqDcsZfkI,2112
|
| 26 |
+
markdown_it/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
|
| 27 |
+
markdown_it/renderer.py,sha256=jZ62oK-y-qaz8o8TDxCUMvS5OavraJ2-1uaWVqrUCv0,9970
|
| 28 |
+
markdown_it/ruler.py,sha256=J18Pru7u77kqJfnMC5oiFWgnw_58vkbfk5hWQBgED7s,9199
|
| 29 |
+
markdown_it/rules_block/__init__.py,sha256=8su1tOxDw_IR9JSdgqfkGZSNdYpZZCBC9MMmFODdbmE,553
|
| 30 |
+
markdown_it/rules_block/blockquote.py,sha256=7uymS36dcrned3DsIaRcqcbFU1NlymhvsZpEXTD3_n8,8887
|
| 31 |
+
markdown_it/rules_block/code.py,sha256=ASAnisg4hS2RhnP_7_1_pjx4NbFSYmrs6lHDgtHPXIo,859
|
| 32 |
+
markdown_it/rules_block/fence.py,sha256=BJgU-PqZ4vAlCqGcrc8UtdLpJJyMeRWN-G-Op-zxrMc,2537
|
| 33 |
+
markdown_it/rules_block/heading.py,sha256=e9NnvXLbY1bvowq_Pd4S-g6LbVg3iCx26qzwv3jLUyE,1746
|
| 34 |
+
markdown_it/rules_block/hr.py,sha256=fPJ-tubFKjxJxhKPiTAxVP-_LHYbAq32iZ52J5sFxOU,1226
|
| 35 |
+
markdown_it/rules_block/html_block.py,sha256=wA8pb34LtZr1BkIATgGKQBIGX5jQNOkwZl9UGEqvb5M,2721
|
| 36 |
+
markdown_it/rules_block/lheading.py,sha256=fWoEuUo7S2svr5UMKmyQMkh0hheYAHg2gMM266Mogs4,2625
|
| 37 |
+
markdown_it/rules_block/list.py,sha256=gIodkAJFyOIyKCZCj5lAlL7jIj5kAzrDb-K-2MFNplY,9668
|
| 38 |
+
markdown_it/rules_block/paragraph.py,sha256=pQqTn8yYDI6_mWX-_m6PXY4wvDQB1nZ4dVUp3gKu1GA,1818
|
| 39 |
+
markdown_it/rules_block/reference.py,sha256=qzR-KJ_60W8ZzuwYGLlO1bgHHVQP4qlYG4yFpOpNlsA,6168
|
| 40 |
+
markdown_it/rules_block/state_block.py,sha256=HowsQyy5hGUibH4HRZWKfLIlXeDUnuWL7kpF0-rSwoM,8422
|
| 41 |
+
markdown_it/rules_block/table.py,sha256=Zjkc0378QtfQzrhrNWC2kVYsGnOLaZyD3dXG1ugfX-s,6987
|
| 42 |
+
markdown_it/rules_core/__init__.py,sha256=JZNOpLZ4i1vR56StidUa-A_As1XtbDwQR0iEErOXyOI,394
|
| 43 |
+
markdown_it/rules_core/block.py,sha256=0_JY1CUy-H2OooFtIEZAACtuoGUMohgxo4Z6A_UinSg,372
|
| 44 |
+
markdown_it/rules_core/inline.py,sha256=9oWmeBhJHE7x47oJcN9yp6UsAZtrEY_A-VmfoMvKld4,325
|
| 45 |
+
markdown_it/rules_core/linkify.py,sha256=mjQqpk_lHLh2Nxw4UFaLxa47Fgi-OHnmDamlgXnhmv0,5141
|
| 46 |
+
markdown_it/rules_core/normalize.py,sha256=qVkBO4elitPzyP_sQENho-ycUl8s4eNZ1zZrsR2AAgk,402
|
| 47 |
+
markdown_it/rules_core/replacements.py,sha256=NHL9MOuEnPuMFPLDtTYDK9yj7F2FSleMr6bPro-ciaQ,3470
|
| 48 |
+
markdown_it/rules_core/smartquotes.py,sha256=CtawEcTHYgzIWZwxIGs8e8oSKhm0B7th2305I3FNEc0,7443
|
| 49 |
+
markdown_it/rules_core/state_core.py,sha256=HqWZCUr5fW7xG6jeQZDdO0hE9hxxyl3_-bawgOy57HY,570
|
| 50 |
+
markdown_it/rules_core/text_join.py,sha256=JVuq_27LoI0IjJDmCXOuRiTs1rmSFhFUUjh6MdF_YCk,1172
|
| 51 |
+
markdown_it/rules_inline/__init__.py,sha256=Zvl8P8V830vDhcQKEleLKZ_paC-ypTn7eWpmFa9yySQ,696
|
| 52 |
+
markdown_it/rules_inline/autolink.py,sha256=l4EY7OLzuda350cT6Du_dggEwcb96TvD7YPXf2H6P1M,2079
|
| 53 |
+
markdown_it/rules_inline/backticks.py,sha256=J7bezjjNxiXlKqvHc0fJkHZwH7-2nBsXVjcKydk8E4M,2037
|
| 54 |
+
markdown_it/rules_inline/balance_pairs.py,sha256=vifasmne02sNaBBwuZsA4yI02vmv1gvVN4qR-b9m62E,4851
|
| 55 |
+
markdown_it/rules_inline/emphasis.py,sha256=7aDLZx0Jlekuvbu3uEUTDhJp00Z0Pj6g4C3-VLhI8Co,3123
|
| 56 |
+
markdown_it/rules_inline/entity.py,sha256=CE8AIGMi5isEa24RNseo0wRmTTaj5YLbgTFdDmBesAU,1651
|
| 57 |
+
markdown_it/rules_inline/escape.py,sha256=5DEa7O6ByUfXdXZudcF7JZwLxXG1njAuXIOUsNDPPqU,1658
|
| 58 |
+
markdown_it/rules_inline/fragments_join.py,sha256=_3JbwWYJz74gRHeZk6T8edVJT2IVSsi7FfmJJlieQlA,1493
|
| 59 |
+
markdown_it/rules_inline/html_inline.py,sha256=SBg6HR0HRqCdrkkec0dfOYuQdAqyfeLRFLeQggtgjvg,1130
|
| 60 |
+
markdown_it/rules_inline/image.py,sha256=AMO7kls5c-C4A_S2rBiIlKD8BQ8vIgyWUX7vCpXy_Qs,4135
|
| 61 |
+
markdown_it/rules_inline/link.py,sha256=wRdTMxjNYFiV6uouZMML3fIPvyFrPtMHWzJNBQcQLV0,4318
|
| 62 |
+
markdown_it/rules_inline/linkify.py,sha256=gmHw59SsMQLImv6v1RkDY9lcQAmTN-UZ4GwRFiR8jlg,1704
|
| 63 |
+
markdown_it/rules_inline/newline.py,sha256=LEIhBB_3PPLeCAgaC2naheMjW5N6b9UaAB6sh47Ckz8,1296
|
| 64 |
+
markdown_it/rules_inline/state_inline.py,sha256=rXmMX0P0pCf-v-013YB24MBQxMn2dJhoSZQMNYAZ8HQ,5101
|
| 65 |
+
markdown_it/rules_inline/strikethrough.py,sha256=pwcPlyhkh5pqFVxRCSrdW5dNCIOtU4eDit7TVDTPIVA,3214
|
| 66 |
+
markdown_it/rules_inline/text.py,sha256=GwmMVZziAmhj48l9VaXAXwzzUKDkhaA14thv-TCaS2M,901
|
| 67 |
+
markdown_it/token.py,sha256=NEvuoYAeDh8_6zT6fukzdoncusVOjyUKw2zjsNgZmp4,6439
|
| 68 |
+
markdown_it/tree.py,sha256=YxSqq3qSuhHHm1nQpPUhyDA4VIWHu_G_92bKdUcXXGM,11421
|
| 69 |
+
markdown_it/utils.py,sha256=zPoQ8lhvxtJfg6iNSim0LcnAL0Y4XnV3G4DIIKmL8OU,5365
|
| 70 |
+
markdown_it_py-3.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 71 |
+
markdown_it_py-3.0.0.dist-info/LICENSE,sha256=SiJg1uLND1oVGh6G2_59PtVSseK-q_mUHBulxJy85IQ,1078
|
| 72 |
+
markdown_it_py-3.0.0.dist-info/LICENSE.markdown-it,sha256=eSxIxahJoV_fnjfovPnm0d0TsytGxkKnSKCkapkZ1HM,1073
|
| 73 |
+
markdown_it_py-3.0.0.dist-info/METADATA,sha256=0-kME4KQNSCGPzfSEFgQc8MhUd5cmG-LO007BFk3_fw,6940
|
| 74 |
+
markdown_it_py-3.0.0.dist-info/RECORD,,
|
| 75 |
+
markdown_it_py-3.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 76 |
+
markdown_it_py-3.0.0.dist-info/WHEEL,sha256=4TfKIB_xu-04bc2iKz6_zFt-gEFEEDU_31HGhqzOCE8,81
|
| 77 |
+
markdown_it_py-3.0.0.dist-info/entry_points.txt,sha256=T81l7fHQ3pllpQ4wUtQK6a8g_p6wxQbnjKVHCk2WMG4,58
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/REQUESTED
ADDED
|
File without changes
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: flit 3.7.1
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
lib/python3.10/site-packages/markdown_it_py-3.0.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
markdown-it=markdown_it.cli.parse:main
|
| 3 |
+
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Araguaina
ADDED
|
Binary file (870 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Argentina/Salta
ADDED
|
Binary file (1.03 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Argentina/Tucuman
ADDED
|
Binary file (1.09 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia
ADDED
|
Binary file (1.06 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Asuncion
ADDED
|
Binary file (1.64 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Belem
ADDED
|
Binary file (562 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Boise
ADDED
|
Binary file (2.41 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Cambridge_Bay
ADDED
|
Binary file (2.25 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Cancun
ADDED
|
Binary file (864 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Dawson
ADDED
|
Binary file (1.61 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Dominica
ADDED
|
Binary file (246 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/El_Salvador
ADDED
|
Binary file (224 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Goose_Bay
ADDED
|
Binary file (3.21 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Grenada
ADDED
|
Binary file (246 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Hermosillo
ADDED
|
Binary file (388 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis
ADDED
|
Binary file (1.68 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Knox
ADDED
|
Binary file (2.44 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Marengo
ADDED
|
Binary file (1.74 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Petersburg
ADDED
|
Binary file (1.92 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Tell_City
ADDED
|
Binary file (1.7 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vevay
ADDED
|
Binary file (1.43 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Vincennes
ADDED
|
Binary file (1.71 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indiana/Winamac
ADDED
|
Binary file (1.79 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Indianapolis
ADDED
|
Binary file (1.68 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Iqaluit
ADDED
|
Binary file (2.2 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Jamaica
ADDED
|
Binary file (482 Bytes). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Jujuy
ADDED
|
Binary file (1.03 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Juneau
ADDED
|
Binary file (2.35 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Kentucky/Louisville
ADDED
|
Binary file (2.79 kB). View file
|
|
|
lib/python3.10/site-packages/pytz/zoneinfo/America/Kentucky/Monticello
ADDED
|
Binary file (2.37 kB). View file
|
|
|