supabase_auth 2.11.3__tar.gz → 2.12.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/PKG-INFO +3 -1
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/pyproject.toml +12 -10
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/gotrue_client.py +117 -17
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/gotrue_client.py +117 -17
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/constants.py +1 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/errors.py +11 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/helpers.py +59 -9
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/types.py +56 -4
- supabase_auth-2.12.0/supabase_auth/version.py +1 -0
- supabase_auth-2.11.3/supabase_auth/_sync/api.py +0 -656
- supabase_auth-2.11.3/supabase_auth/_sync/client.py +0 -661
- supabase_auth-2.11.3/supabase_auth/version.py +0 -1
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/LICENSE +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/README.md +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/__init__.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/__init__.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/gotrue_admin_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/gotrue_admin_mfa_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/gotrue_base_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/gotrue_mfa_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_async/storage.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/__init__.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/gotrue_admin_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/gotrue_admin_mfa_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/gotrue_base_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/gotrue_mfa_api.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/_sync/storage.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/http_clients.py +0 -0
- {supabase_auth-2.11.3 → supabase_auth-2.12.0}/supabase_auth/timer.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: supabase_auth
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.12.0
|
|
4
4
|
Summary: Python Client Library for Supabase Auth
|
|
5
5
|
Home-page: https://github.com/supabase/auth-py
|
|
6
6
|
License: MIT
|
|
@@ -17,6 +17,8 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.13
|
|
18
18
|
Requires-Dist: httpx[http2] (>=0.26,<0.29)
|
|
19
19
|
Requires-Dist: pydantic (>=1.10,<3)
|
|
20
|
+
Requires-Dist: pyjwt (>=2.10.1,<3.0.0)
|
|
21
|
+
Requires-Dist: pytest-mock (>=3.14.0,<4.0.0)
|
|
20
22
|
Project-URL: Documentation, https://github.com/supabase/auth-py
|
|
21
23
|
Project-URL: Repository, https://github.com/supabase/auth-py
|
|
22
24
|
Description-Content-Type: text/markdown
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "supabase_auth"
|
|
3
|
-
version = "2.
|
|
3
|
+
version = "2.12.0" # {x-release-please-version}
|
|
4
4
|
description = "Python Client Library for Supabase Auth"
|
|
5
5
|
authors = ["Joel Lee <joel@joellee.org>"]
|
|
6
6
|
homepage = "https://github.com/supabase/auth-py"
|
|
@@ -11,25 +11,27 @@ license = "MIT"
|
|
|
11
11
|
classifiers = [
|
|
12
12
|
"Programming Language :: Python :: 3",
|
|
13
13
|
"License :: OSI Approved :: MIT License",
|
|
14
|
-
"Operating System :: OS Independent"
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
15
|
]
|
|
16
16
|
|
|
17
17
|
[tool.poetry.dependencies]
|
|
18
18
|
python = "^3.9"
|
|
19
|
-
httpx = {version = ">=0.26,<0.29", extras = ["http2"]}
|
|
19
|
+
httpx = { version = ">=0.26,<0.29", extras = ["http2"] }
|
|
20
20
|
pydantic = ">=1.10,<3"
|
|
21
|
+
pyjwt = "^2.10.1"
|
|
22
|
+
pytest-mock = "^3.14.0"
|
|
21
23
|
|
|
22
24
|
[tool.poetry.dev-dependencies]
|
|
23
|
-
pytest = "^8.3.
|
|
24
|
-
flake8 = "^7.1.
|
|
25
|
+
pytest = "^8.3.5"
|
|
26
|
+
flake8 = "^7.1.2"
|
|
25
27
|
black = "^25.1.0"
|
|
26
|
-
isort = "^6.0.
|
|
27
|
-
pre-commit = "^4.
|
|
28
|
+
isort = "^6.0.1"
|
|
29
|
+
pre-commit = "^4.2.0"
|
|
28
30
|
pytest-cov = "^6.0.0"
|
|
29
31
|
pytest-depends = "^1.0.1"
|
|
30
|
-
pytest-asyncio = "^0.
|
|
31
|
-
Faker = "^
|
|
32
|
-
unasync-cli = "
|
|
32
|
+
pytest-asyncio = "^0.26.0"
|
|
33
|
+
Faker = "^37.1.0"
|
|
34
|
+
unasync-cli = { git = "https://github.com/supabase-community/unasync-cli.git", branch = "main" }
|
|
33
35
|
|
|
34
36
|
[tool.poetry.group.dev.dependencies]
|
|
35
37
|
pygithub = ">=1.57,<3.0"
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import time
|
|
3
4
|
from contextlib import suppress
|
|
4
5
|
from functools import partial
|
|
5
6
|
from json import loads
|
|
6
|
-
from time import time
|
|
7
7
|
from typing import Callable, Dict, List, Optional, Tuple
|
|
8
8
|
from urllib.parse import parse_qs, urlencode, urlparse
|
|
9
9
|
from uuid import uuid4
|
|
10
10
|
|
|
11
|
+
from jwt import get_algorithm_by_name
|
|
12
|
+
|
|
11
13
|
from ..constants import (
|
|
12
14
|
DEFAULT_HEADERS,
|
|
13
15
|
EXPIRY_MARGIN,
|
|
@@ -20,11 +22,12 @@ from ..errors import (
|
|
|
20
22
|
AuthApiError,
|
|
21
23
|
AuthImplicitGrantRedirectError,
|
|
22
24
|
AuthInvalidCredentialsError,
|
|
25
|
+
AuthInvalidJwtError,
|
|
23
26
|
AuthRetryableError,
|
|
24
27
|
AuthSessionMissingError,
|
|
25
28
|
)
|
|
26
29
|
from ..helpers import (
|
|
27
|
-
|
|
30
|
+
decode_jwt,
|
|
28
31
|
generate_pkce_challenge,
|
|
29
32
|
generate_pkce_verifier,
|
|
30
33
|
model_dump,
|
|
@@ -32,13 +35,16 @@ from ..helpers import (
|
|
|
32
35
|
model_validate,
|
|
33
36
|
parse_auth_otp_response,
|
|
34
37
|
parse_auth_response,
|
|
38
|
+
parse_jwks,
|
|
35
39
|
parse_link_identity_response,
|
|
36
40
|
parse_sso_response,
|
|
37
41
|
parse_user_response,
|
|
42
|
+
validate_exp,
|
|
38
43
|
)
|
|
39
44
|
from ..http_clients import AsyncClient
|
|
40
45
|
from ..timer import Timer
|
|
41
46
|
from ..types import (
|
|
47
|
+
JWK,
|
|
42
48
|
AuthChangeEvent,
|
|
43
49
|
AuthenticatorAssuranceLevels,
|
|
44
50
|
AuthFlowType,
|
|
@@ -50,9 +56,10 @@ from ..types import (
|
|
|
50
56
|
AuthMFAVerifyResponse,
|
|
51
57
|
AuthOtpResponse,
|
|
52
58
|
AuthResponse,
|
|
59
|
+
ClaimsResponse,
|
|
53
60
|
CodeExchangeParams,
|
|
54
|
-
DecodedJWTDict,
|
|
55
61
|
IdentitiesResponse,
|
|
62
|
+
JWKSet,
|
|
56
63
|
MFAChallengeAndVerifyParams,
|
|
57
64
|
MFAChallengeParams,
|
|
58
65
|
MFAEnrollParams,
|
|
@@ -106,6 +113,11 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
106
113
|
verify=verify,
|
|
107
114
|
proxy=proxy,
|
|
108
115
|
)
|
|
116
|
+
|
|
117
|
+
self._jwks: JWKSet = {"keys": []}
|
|
118
|
+
self._jwks_ttl: float = 600 # 10 minutes
|
|
119
|
+
self._jwks_cached_at: Optional[float] = None
|
|
120
|
+
|
|
109
121
|
self._storage_key = storage_key or STORAGE_KEY
|
|
110
122
|
self._auto_refresh_token = auto_refresh_token
|
|
111
123
|
self._persist_session = persist_session
|
|
@@ -608,7 +620,7 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
608
620
|
current_session = self._in_memory_session
|
|
609
621
|
if not current_session:
|
|
610
622
|
return None
|
|
611
|
-
time_now = round(time())
|
|
623
|
+
time_now = round(time.time())
|
|
612
624
|
has_expired = (
|
|
613
625
|
current_session.expires_at <= time_now + EXPIRY_MARGIN
|
|
614
626
|
if current_session.expires_at
|
|
@@ -669,12 +681,12 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
669
681
|
The current session that minimally contains an access token,
|
|
670
682
|
refresh token and a user.
|
|
671
683
|
"""
|
|
672
|
-
time_now = round(time())
|
|
684
|
+
time_now = round(time.time())
|
|
673
685
|
expires_at = time_now
|
|
674
686
|
has_expired = True
|
|
675
687
|
session: Optional[Session] = None
|
|
676
688
|
if access_token and access_token.split(".")[1]:
|
|
677
|
-
payload =
|
|
689
|
+
payload = decode_jwt(access_token)["payload"]
|
|
678
690
|
exp = payload.get("exp")
|
|
679
691
|
if exp:
|
|
680
692
|
expires_at = int(exp)
|
|
@@ -866,7 +878,7 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
866
878
|
"DELETE",
|
|
867
879
|
f"factors/{params.get('factor_id')}",
|
|
868
880
|
jwt=session.access_token,
|
|
869
|
-
xform=partial(
|
|
881
|
+
xform=partial(model_validate, AuthMFAUnenrollResponse),
|
|
870
882
|
)
|
|
871
883
|
|
|
872
884
|
async def _list_factors(self) -> AuthMFAListFactorsResponse:
|
|
@@ -886,7 +898,7 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
886
898
|
next_level=None,
|
|
887
899
|
current_authentication_methods=[],
|
|
888
900
|
)
|
|
889
|
-
payload =
|
|
901
|
+
payload = decode_jwt(session.access_token)["payload"]
|
|
890
902
|
current_level: Optional[AuthenticatorAssuranceLevels] = None
|
|
891
903
|
if payload.get("aal"):
|
|
892
904
|
current_level = payload.get("aal")
|
|
@@ -946,7 +958,7 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
946
958
|
token_type = self._get_param(params, "token_type")
|
|
947
959
|
if not token_type:
|
|
948
960
|
raise AuthImplicitGrantRedirectError("No token_type detected.")
|
|
949
|
-
time_now = round(time())
|
|
961
|
+
time_now = round(time.time())
|
|
950
962
|
expires_at = time_now + int(expires_in)
|
|
951
963
|
user = await self.get_user(access_token)
|
|
952
964
|
session = Session(
|
|
@@ -969,7 +981,7 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
969
981
|
if raw_session:
|
|
970
982
|
await self._remove_session()
|
|
971
983
|
return
|
|
972
|
-
time_now = round(time())
|
|
984
|
+
time_now = round(time.time())
|
|
973
985
|
expires_at = current_session.expires_at
|
|
974
986
|
if expires_at and expires_at < time_now + EXPIRY_MARGIN:
|
|
975
987
|
refresh_token = current_session.refresh_token
|
|
@@ -1021,7 +1033,7 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
1021
1033
|
self._in_memory_session = session
|
|
1022
1034
|
expire_at = session.expires_at
|
|
1023
1035
|
if expire_at:
|
|
1024
|
-
time_now = round(time())
|
|
1036
|
+
time_now = round(time.time())
|
|
1025
1037
|
expire_in = expire_at - time_now
|
|
1026
1038
|
refresh_duration_before_expires = (
|
|
1027
1039
|
EXPIRY_MARGIN if expire_in > EXPIRY_MARGIN else 0.5
|
|
@@ -1124,12 +1136,6 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
1124
1136
|
query = urlencode(params)
|
|
1125
1137
|
return f"{url}?{query}", params
|
|
1126
1138
|
|
|
1127
|
-
def _decode_jwt(self, jwt: str) -> DecodedJWTDict:
|
|
1128
|
-
"""
|
|
1129
|
-
Decodes a JWT (without performing any validation).
|
|
1130
|
-
"""
|
|
1131
|
-
return decode_jwt_payload(jwt)
|
|
1132
|
-
|
|
1133
1139
|
async def exchange_code_for_session(self, params: CodeExchangeParams):
|
|
1134
1140
|
code_verifier = params.get("code_verifier") or await self._storage.get_item(
|
|
1135
1141
|
f"{self._storage_key}-code-verifier"
|
|
@@ -1150,3 +1156,97 @@ class AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
|
1150
1156
|
await self._save_session(response.session)
|
|
1151
1157
|
self._notify_all_subscribers("SIGNED_IN", response.session)
|
|
1152
1158
|
return response
|
|
1159
|
+
|
|
1160
|
+
async def _fetch_jwks(self, kid: str, jwks: JWKSet) -> JWK:
|
|
1161
|
+
jwk: Optional[JWK] = None
|
|
1162
|
+
|
|
1163
|
+
# try fetching from the suplied keys.
|
|
1164
|
+
jwk = next((jwk for jwk in jwks["keys"] if jwk["kid"] == kid), None)
|
|
1165
|
+
|
|
1166
|
+
if jwk:
|
|
1167
|
+
return jwk
|
|
1168
|
+
|
|
1169
|
+
if self._jwks and (
|
|
1170
|
+
self._jwks_cached_at and time.time() - self._jwks_cached_at < self._jwks_ttl
|
|
1171
|
+
):
|
|
1172
|
+
# try fetching from the cache.
|
|
1173
|
+
jwk = next(
|
|
1174
|
+
(jwk for jwk in self._jwks["keys"] if jwk["kid"] == kid),
|
|
1175
|
+
None,
|
|
1176
|
+
)
|
|
1177
|
+
if jwk:
|
|
1178
|
+
return jwk
|
|
1179
|
+
|
|
1180
|
+
# jwk isn't cached in memory so we need to fetch it from the well-known endpoint
|
|
1181
|
+
response = await self._request("GET", ".well-known/jwks.json", xform=parse_jwks)
|
|
1182
|
+
if response:
|
|
1183
|
+
self._jwks = response
|
|
1184
|
+
self._jwks_cached_at = time.time()
|
|
1185
|
+
|
|
1186
|
+
# find the signing key
|
|
1187
|
+
jwk = next((jwk for jwk in response["keys"] if jwk["kid"] == kid), None)
|
|
1188
|
+
if not jwk:
|
|
1189
|
+
raise AuthInvalidJwtError("No matching signing key found in JWKS")
|
|
1190
|
+
|
|
1191
|
+
return jwk
|
|
1192
|
+
|
|
1193
|
+
raise AuthInvalidJwtError("JWT has no valid kid")
|
|
1194
|
+
|
|
1195
|
+
async def get_claims(
|
|
1196
|
+
self, jwt: Optional[str] = None, jwks: Optional[JWKSet] = None
|
|
1197
|
+
) -> Optional[ClaimsResponse]:
|
|
1198
|
+
token = jwt
|
|
1199
|
+
if not token:
|
|
1200
|
+
session = await self.get_session()
|
|
1201
|
+
if not session:
|
|
1202
|
+
return None
|
|
1203
|
+
|
|
1204
|
+
token = session.access_token
|
|
1205
|
+
|
|
1206
|
+
decoded_jwt = decode_jwt(token)
|
|
1207
|
+
|
|
1208
|
+
payload, header, signature = (
|
|
1209
|
+
decoded_jwt["payload"],
|
|
1210
|
+
decoded_jwt["header"],
|
|
1211
|
+
decoded_jwt["signature"],
|
|
1212
|
+
)
|
|
1213
|
+
raw_header, raw_payload = (
|
|
1214
|
+
decoded_jwt["raw"]["header"],
|
|
1215
|
+
decoded_jwt["raw"]["payload"],
|
|
1216
|
+
)
|
|
1217
|
+
|
|
1218
|
+
validate_exp(payload["exp"])
|
|
1219
|
+
|
|
1220
|
+
# if symmetric algorithm, fallback to get_user
|
|
1221
|
+
if "kid" not in header or header["alg"] == "HS256":
|
|
1222
|
+
await self.get_user(token)
|
|
1223
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1224
|
+
|
|
1225
|
+
algorithm = get_algorithm_by_name(header["alg"])
|
|
1226
|
+
signing_key = algorithm.from_jwk(
|
|
1227
|
+
await self._fetch_jwks(header["kid"], jwks or {"keys": []})
|
|
1228
|
+
)
|
|
1229
|
+
|
|
1230
|
+
# verify the signature
|
|
1231
|
+
is_valid = algorithm.verify(
|
|
1232
|
+
msg=f"{raw_header}.{raw_payload}".encode(), key=signing_key, sig=signature
|
|
1233
|
+
)
|
|
1234
|
+
|
|
1235
|
+
if not is_valid:
|
|
1236
|
+
raise AuthInvalidJwtError("Invalid JWT signature")
|
|
1237
|
+
|
|
1238
|
+
# If verification succeeds, decode and return claims
|
|
1239
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1240
|
+
|
|
1241
|
+
def __del__(self) -> None:
|
|
1242
|
+
"""Clean up resources when the client is destroyed."""
|
|
1243
|
+
if self._refresh_token_timer:
|
|
1244
|
+
try:
|
|
1245
|
+
# Try to cancel the timer
|
|
1246
|
+
self._refresh_token_timer.cancel()
|
|
1247
|
+
except:
|
|
1248
|
+
# Ignore errors if event loop is closed or selector is not registered
|
|
1249
|
+
pass
|
|
1250
|
+
finally:
|
|
1251
|
+
# Always set to None to prevent further attempts
|
|
1252
|
+
self._refresh_token_timer = None
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import time
|
|
3
4
|
from contextlib import suppress
|
|
4
5
|
from functools import partial
|
|
5
6
|
from json import loads
|
|
6
|
-
from time import time
|
|
7
7
|
from typing import Callable, Dict, List, Optional, Tuple
|
|
8
8
|
from urllib.parse import parse_qs, urlencode, urlparse
|
|
9
9
|
from uuid import uuid4
|
|
10
10
|
|
|
11
|
+
from jwt import get_algorithm_by_name
|
|
12
|
+
|
|
11
13
|
from ..constants import (
|
|
12
14
|
DEFAULT_HEADERS,
|
|
13
15
|
EXPIRY_MARGIN,
|
|
@@ -20,11 +22,12 @@ from ..errors import (
|
|
|
20
22
|
AuthApiError,
|
|
21
23
|
AuthImplicitGrantRedirectError,
|
|
22
24
|
AuthInvalidCredentialsError,
|
|
25
|
+
AuthInvalidJwtError,
|
|
23
26
|
AuthRetryableError,
|
|
24
27
|
AuthSessionMissingError,
|
|
25
28
|
)
|
|
26
29
|
from ..helpers import (
|
|
27
|
-
|
|
30
|
+
decode_jwt,
|
|
28
31
|
generate_pkce_challenge,
|
|
29
32
|
generate_pkce_verifier,
|
|
30
33
|
model_dump,
|
|
@@ -32,13 +35,16 @@ from ..helpers import (
|
|
|
32
35
|
model_validate,
|
|
33
36
|
parse_auth_otp_response,
|
|
34
37
|
parse_auth_response,
|
|
38
|
+
parse_jwks,
|
|
35
39
|
parse_link_identity_response,
|
|
36
40
|
parse_sso_response,
|
|
37
41
|
parse_user_response,
|
|
42
|
+
validate_exp,
|
|
38
43
|
)
|
|
39
44
|
from ..http_clients import SyncClient
|
|
40
45
|
from ..timer import Timer
|
|
41
46
|
from ..types import (
|
|
47
|
+
JWK,
|
|
42
48
|
AuthChangeEvent,
|
|
43
49
|
AuthenticatorAssuranceLevels,
|
|
44
50
|
AuthFlowType,
|
|
@@ -50,9 +56,10 @@ from ..types import (
|
|
|
50
56
|
AuthMFAVerifyResponse,
|
|
51
57
|
AuthOtpResponse,
|
|
52
58
|
AuthResponse,
|
|
59
|
+
ClaimsResponse,
|
|
53
60
|
CodeExchangeParams,
|
|
54
|
-
DecodedJWTDict,
|
|
55
61
|
IdentitiesResponse,
|
|
62
|
+
JWKSet,
|
|
56
63
|
MFAChallengeAndVerifyParams,
|
|
57
64
|
MFAChallengeParams,
|
|
58
65
|
MFAEnrollParams,
|
|
@@ -106,6 +113,11 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
106
113
|
verify=verify,
|
|
107
114
|
proxy=proxy,
|
|
108
115
|
)
|
|
116
|
+
|
|
117
|
+
self._jwks: JWKSet = {"keys": []}
|
|
118
|
+
self._jwks_ttl: float = 600 # 10 minutes
|
|
119
|
+
self._jwks_cached_at: Optional[float] = None
|
|
120
|
+
|
|
109
121
|
self._storage_key = storage_key or STORAGE_KEY
|
|
110
122
|
self._auto_refresh_token = auto_refresh_token
|
|
111
123
|
self._persist_session = persist_session
|
|
@@ -606,7 +618,7 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
606
618
|
current_session = self._in_memory_session
|
|
607
619
|
if not current_session:
|
|
608
620
|
return None
|
|
609
|
-
time_now = round(time())
|
|
621
|
+
time_now = round(time.time())
|
|
610
622
|
has_expired = (
|
|
611
623
|
current_session.expires_at <= time_now + EXPIRY_MARGIN
|
|
612
624
|
if current_session.expires_at
|
|
@@ -667,12 +679,12 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
667
679
|
The current session that minimally contains an access token,
|
|
668
680
|
refresh token and a user.
|
|
669
681
|
"""
|
|
670
|
-
time_now = round(time())
|
|
682
|
+
time_now = round(time.time())
|
|
671
683
|
expires_at = time_now
|
|
672
684
|
has_expired = True
|
|
673
685
|
session: Optional[Session] = None
|
|
674
686
|
if access_token and access_token.split(".")[1]:
|
|
675
|
-
payload =
|
|
687
|
+
payload = decode_jwt(access_token)["payload"]
|
|
676
688
|
exp = payload.get("exp")
|
|
677
689
|
if exp:
|
|
678
690
|
expires_at = int(exp)
|
|
@@ -862,7 +874,7 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
862
874
|
"DELETE",
|
|
863
875
|
f"factors/{params.get('factor_id')}",
|
|
864
876
|
jwt=session.access_token,
|
|
865
|
-
xform=partial(
|
|
877
|
+
xform=partial(model_validate, AuthMFAUnenrollResponse),
|
|
866
878
|
)
|
|
867
879
|
|
|
868
880
|
def _list_factors(self) -> AuthMFAListFactorsResponse:
|
|
@@ -882,7 +894,7 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
882
894
|
next_level=None,
|
|
883
895
|
current_authentication_methods=[],
|
|
884
896
|
)
|
|
885
|
-
payload =
|
|
897
|
+
payload = decode_jwt(session.access_token)["payload"]
|
|
886
898
|
current_level: Optional[AuthenticatorAssuranceLevels] = None
|
|
887
899
|
if payload.get("aal"):
|
|
888
900
|
current_level = payload.get("aal")
|
|
@@ -942,7 +954,7 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
942
954
|
token_type = self._get_param(params, "token_type")
|
|
943
955
|
if not token_type:
|
|
944
956
|
raise AuthImplicitGrantRedirectError("No token_type detected.")
|
|
945
|
-
time_now = round(time())
|
|
957
|
+
time_now = round(time.time())
|
|
946
958
|
expires_at = time_now + int(expires_in)
|
|
947
959
|
user = self.get_user(access_token)
|
|
948
960
|
session = Session(
|
|
@@ -965,7 +977,7 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
965
977
|
if raw_session:
|
|
966
978
|
self._remove_session()
|
|
967
979
|
return
|
|
968
|
-
time_now = round(time())
|
|
980
|
+
time_now = round(time.time())
|
|
969
981
|
expires_at = current_session.expires_at
|
|
970
982
|
if expires_at and expires_at < time_now + EXPIRY_MARGIN:
|
|
971
983
|
refresh_token = current_session.refresh_token
|
|
@@ -1017,7 +1029,7 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
1017
1029
|
self._in_memory_session = session
|
|
1018
1030
|
expire_at = session.expires_at
|
|
1019
1031
|
if expire_at:
|
|
1020
|
-
time_now = round(time())
|
|
1032
|
+
time_now = round(time.time())
|
|
1021
1033
|
expire_in = expire_at - time_now
|
|
1022
1034
|
refresh_duration_before_expires = (
|
|
1023
1035
|
EXPIRY_MARGIN if expire_in > EXPIRY_MARGIN else 0.5
|
|
@@ -1118,12 +1130,6 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
1118
1130
|
query = urlencode(params)
|
|
1119
1131
|
return f"{url}?{query}", params
|
|
1120
1132
|
|
|
1121
|
-
def _decode_jwt(self, jwt: str) -> DecodedJWTDict:
|
|
1122
|
-
"""
|
|
1123
|
-
Decodes a JWT (without performing any validation).
|
|
1124
|
-
"""
|
|
1125
|
-
return decode_jwt_payload(jwt)
|
|
1126
|
-
|
|
1127
1133
|
def exchange_code_for_session(self, params: CodeExchangeParams):
|
|
1128
1134
|
code_verifier = params.get("code_verifier") or self._storage.get_item(
|
|
1129
1135
|
f"{self._storage_key}-code-verifier"
|
|
@@ -1144,3 +1150,97 @@ class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
|
1144
1150
|
self._save_session(response.session)
|
|
1145
1151
|
self._notify_all_subscribers("SIGNED_IN", response.session)
|
|
1146
1152
|
return response
|
|
1153
|
+
|
|
1154
|
+
def _fetch_jwks(self, kid: str, jwks: JWKSet) -> JWK:
|
|
1155
|
+
jwk: Optional[JWK] = None
|
|
1156
|
+
|
|
1157
|
+
# try fetching from the suplied keys.
|
|
1158
|
+
jwk = next((jwk for jwk in jwks["keys"] if jwk["kid"] == kid), None)
|
|
1159
|
+
|
|
1160
|
+
if jwk:
|
|
1161
|
+
return jwk
|
|
1162
|
+
|
|
1163
|
+
if self._jwks and (
|
|
1164
|
+
self._jwks_cached_at and time.time() - self._jwks_cached_at < self._jwks_ttl
|
|
1165
|
+
):
|
|
1166
|
+
# try fetching from the cache.
|
|
1167
|
+
jwk = next(
|
|
1168
|
+
(jwk for jwk in self._jwks["keys"] if jwk["kid"] == kid),
|
|
1169
|
+
None,
|
|
1170
|
+
)
|
|
1171
|
+
if jwk:
|
|
1172
|
+
return jwk
|
|
1173
|
+
|
|
1174
|
+
# jwk isn't cached in memory so we need to fetch it from the well-known endpoint
|
|
1175
|
+
response = self._request("GET", ".well-known/jwks.json", xform=parse_jwks)
|
|
1176
|
+
if response:
|
|
1177
|
+
self._jwks = response
|
|
1178
|
+
self._jwks_cached_at = time.time()
|
|
1179
|
+
|
|
1180
|
+
# find the signing key
|
|
1181
|
+
jwk = next((jwk for jwk in response["keys"] if jwk["kid"] == kid), None)
|
|
1182
|
+
if not jwk:
|
|
1183
|
+
raise AuthInvalidJwtError("No matching signing key found in JWKS")
|
|
1184
|
+
|
|
1185
|
+
return jwk
|
|
1186
|
+
|
|
1187
|
+
raise AuthInvalidJwtError("JWT has no valid kid")
|
|
1188
|
+
|
|
1189
|
+
def get_claims(
|
|
1190
|
+
self, jwt: Optional[str] = None, jwks: Optional[JWKSet] = None
|
|
1191
|
+
) -> Optional[ClaimsResponse]:
|
|
1192
|
+
token = jwt
|
|
1193
|
+
if not token:
|
|
1194
|
+
session = self.get_session()
|
|
1195
|
+
if not session:
|
|
1196
|
+
return None
|
|
1197
|
+
|
|
1198
|
+
token = session.access_token
|
|
1199
|
+
|
|
1200
|
+
decoded_jwt = decode_jwt(token)
|
|
1201
|
+
|
|
1202
|
+
payload, header, signature = (
|
|
1203
|
+
decoded_jwt["payload"],
|
|
1204
|
+
decoded_jwt["header"],
|
|
1205
|
+
decoded_jwt["signature"],
|
|
1206
|
+
)
|
|
1207
|
+
raw_header, raw_payload = (
|
|
1208
|
+
decoded_jwt["raw"]["header"],
|
|
1209
|
+
decoded_jwt["raw"]["payload"],
|
|
1210
|
+
)
|
|
1211
|
+
|
|
1212
|
+
validate_exp(payload["exp"])
|
|
1213
|
+
|
|
1214
|
+
# if symmetric algorithm, fallback to get_user
|
|
1215
|
+
if "kid" not in header or header["alg"] == "HS256":
|
|
1216
|
+
self.get_user(token)
|
|
1217
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1218
|
+
|
|
1219
|
+
algorithm = get_algorithm_by_name(header["alg"])
|
|
1220
|
+
signing_key = algorithm.from_jwk(
|
|
1221
|
+
self._fetch_jwks(header["kid"], jwks or {"keys": []})
|
|
1222
|
+
)
|
|
1223
|
+
|
|
1224
|
+
# verify the signature
|
|
1225
|
+
is_valid = algorithm.verify(
|
|
1226
|
+
msg=f"{raw_header}.{raw_payload}".encode(), key=signing_key, sig=signature
|
|
1227
|
+
)
|
|
1228
|
+
|
|
1229
|
+
if not is_valid:
|
|
1230
|
+
raise AuthInvalidJwtError("Invalid JWT signature")
|
|
1231
|
+
|
|
1232
|
+
# If verification succeeds, decode and return claims
|
|
1233
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1234
|
+
|
|
1235
|
+
def __del__(self) -> None:
|
|
1236
|
+
"""Clean up resources when the client is destroyed."""
|
|
1237
|
+
if self._refresh_token_timer:
|
|
1238
|
+
try:
|
|
1239
|
+
# Try to cancel the timer
|
|
1240
|
+
self._refresh_token_timer.cancel()
|
|
1241
|
+
except:
|
|
1242
|
+
# Ignore errors if event loop is closed or selector is not registered
|
|
1243
|
+
pass
|
|
1244
|
+
finally:
|
|
1245
|
+
# Always set to None to prevent further attempts
|
|
1246
|
+
self._refresh_token_timer = None
|
|
@@ -225,3 +225,14 @@ class AuthWeakPasswordError(CustomAuthError):
|
|
|
225
225
|
"status": self.status,
|
|
226
226
|
"reasons": self.reasons,
|
|
227
227
|
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class AuthInvalidJwtError(CustomAuthError):
|
|
231
|
+
def __init__(self, message: str) -> None:
|
|
232
|
+
CustomAuthError.__init__(
|
|
233
|
+
self,
|
|
234
|
+
message,
|
|
235
|
+
"AuthInvalidJwtError",
|
|
236
|
+
400,
|
|
237
|
+
"invalid_jwt",
|
|
238
|
+
)
|
|
@@ -8,16 +8,17 @@ import string
|
|
|
8
8
|
from base64 import urlsafe_b64decode
|
|
9
9
|
from datetime import datetime
|
|
10
10
|
from json import loads
|
|
11
|
-
from typing import Any, Dict, Optional, Type, TypeVar, cast
|
|
11
|
+
from typing import Any, Dict, Optional, Type, TypedDict, TypeVar, cast
|
|
12
12
|
from urllib.parse import urlparse
|
|
13
13
|
|
|
14
14
|
from httpx import HTTPStatusError, Response
|
|
15
15
|
from pydantic import BaseModel
|
|
16
16
|
|
|
17
|
-
from .constants import API_VERSION_HEADER_NAME, API_VERSIONS
|
|
17
|
+
from .constants import API_VERSION_HEADER_NAME, API_VERSIONS, BASE64URL_REGEX
|
|
18
18
|
from .errors import (
|
|
19
19
|
AuthApiError,
|
|
20
20
|
AuthError,
|
|
21
|
+
AuthInvalidJwtError,
|
|
21
22
|
AuthRetryableError,
|
|
22
23
|
AuthUnknownError,
|
|
23
24
|
AuthWeakPasswordError,
|
|
@@ -27,6 +28,9 @@ from .types import (
|
|
|
27
28
|
AuthResponse,
|
|
28
29
|
GenerateLinkProperties,
|
|
29
30
|
GenerateLinkResponse,
|
|
31
|
+
JWKSet,
|
|
32
|
+
JWTHeader,
|
|
33
|
+
JWTPayload,
|
|
30
34
|
LinkIdentityResponse,
|
|
31
35
|
Session,
|
|
32
36
|
SSOResponse,
|
|
@@ -35,7 +39,6 @@ from .types import (
|
|
|
35
39
|
)
|
|
36
40
|
|
|
37
41
|
TBaseModel = TypeVar("TBaseModel", bound=BaseModel)
|
|
38
|
-
BASE64URL_REGEX = r"^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$"
|
|
39
42
|
|
|
40
43
|
|
|
41
44
|
def model_validate(model: Type[TBaseModel], contents) -> TBaseModel:
|
|
@@ -117,6 +120,13 @@ def parse_sso_response(data: Any) -> SSOResponse:
|
|
|
117
120
|
return model_validate(SSOResponse, data)
|
|
118
121
|
|
|
119
122
|
|
|
123
|
+
def parse_jwks(response: Any) -> JWKSet:
|
|
124
|
+
if "keys" not in response or len(response["keys"]) == 0:
|
|
125
|
+
raise AuthInvalidJwtError("JWKS is empty")
|
|
126
|
+
|
|
127
|
+
return {"keys": response["keys"]}
|
|
128
|
+
|
|
129
|
+
|
|
120
130
|
def get_error_message(error: Any) -> str:
|
|
121
131
|
props = ["msg", "message", "error_description", "error"]
|
|
122
132
|
filter = lambda prop: (
|
|
@@ -192,15 +202,46 @@ def handle_exception(exception: Exception) -> AuthError:
|
|
|
192
202
|
return AuthUnknownError(get_error_message(error), e)
|
|
193
203
|
|
|
194
204
|
|
|
195
|
-
def
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
205
|
+
def str_from_base64url(base64url: str) -> str:
|
|
206
|
+
# Addding padding otherwise the following error happens:
|
|
207
|
+
# binascii.Error: Incorrect padding
|
|
208
|
+
base64url_with_padding = base64url + "=" * (-len(base64url) % 4)
|
|
209
|
+
return urlsafe_b64decode(base64url_with_padding).decode("utf-8")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def base64url_to_bytes(base64url: str) -> bytes:
|
|
200
213
|
# Addding padding otherwise the following error happens:
|
|
201
214
|
# binascii.Error: Incorrect padding
|
|
202
215
|
base64url_with_padding = base64url + "=" * (-len(base64url) % 4)
|
|
203
|
-
return
|
|
216
|
+
return urlsafe_b64decode(base64url_with_padding)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class DecodedJWT(TypedDict):
|
|
220
|
+
header: JWTHeader
|
|
221
|
+
payload: JWTPayload
|
|
222
|
+
signature: bytes
|
|
223
|
+
raw: Dict[str, str]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def decode_jwt(token: str) -> DecodedJWT:
|
|
227
|
+
parts = token.split(".")
|
|
228
|
+
if len(parts) != 3:
|
|
229
|
+
raise AuthInvalidJwtError("Invalid JWT structure")
|
|
230
|
+
|
|
231
|
+
# regex check for base64url
|
|
232
|
+
for part in parts:
|
|
233
|
+
if not re.match(BASE64URL_REGEX, part, re.IGNORECASE):
|
|
234
|
+
raise AuthInvalidJwtError("JWT not in base64url format")
|
|
235
|
+
|
|
236
|
+
return DecodedJWT(
|
|
237
|
+
header=JWTHeader(**loads(str_from_base64url(parts[0]))),
|
|
238
|
+
payload=JWTPayload(**loads(str_from_base64url(parts[1]))),
|
|
239
|
+
signature=base64url_to_bytes(parts[2]),
|
|
240
|
+
raw={
|
|
241
|
+
"header": parts[0],
|
|
242
|
+
"payload": parts[1],
|
|
243
|
+
},
|
|
244
|
+
)
|
|
204
245
|
|
|
205
246
|
|
|
206
247
|
def generate_pkce_verifier(length=64):
|
|
@@ -267,3 +308,12 @@ def is_valid_jwt(value: str) -> bool:
|
|
|
267
308
|
return False
|
|
268
309
|
|
|
269
310
|
return True
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def validate_exp(exp: int) -> None:
|
|
314
|
+
if not exp:
|
|
315
|
+
raise AuthInvalidJwtError("JWT has no expiration time")
|
|
316
|
+
|
|
317
|
+
time_now = datetime.now().timestamp()
|
|
318
|
+
if exp <= time_now:
|
|
319
|
+
raise AuthInvalidJwtError("JWT has expired")
|