usso 0.28.14__py3-none-any.whl → 0.28.16__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- usso/auth/api_key.py +3 -3
- usso/auth/authorization.py +183 -0
- usso/auth/client.py +1 -1
- usso/integrations/django/middleware.py +2 -2
- usso/session/async_session.py +2 -2
- usso/session/base_session.py +3 -3
- usso/session/session.py +1 -1
- {usso-0.28.14.dist-info → usso-0.28.16.dist-info}/METADATA +3 -3
- {usso-0.28.14.dist-info → usso-0.28.16.dist-info}/RECORD +13 -12
- {usso-0.28.14.dist-info → usso-0.28.16.dist-info}/WHEEL +0 -0
- {usso-0.28.14.dist-info → usso-0.28.16.dist-info}/entry_points.txt +0 -0
- {usso-0.28.14.dist-info → usso-0.28.16.dist-info}/licenses/LICENSE.txt +0 -0
- {usso-0.28.14.dist-info → usso-0.28.16.dist-info}/top_level.txt +0 -0
usso/auth/api_key.py
CHANGED
@@ -20,11 +20,11 @@ def _handle_exception(error_type: str, **kwargs):
|
|
20
20
|
|
21
21
|
|
22
22
|
@cachetools.func.ttl_cache(maxsize=128, ttl=10 * 60)
|
23
|
-
def fetch_api_key_data(
|
23
|
+
def fetch_api_key_data(jwks_url: str, api_key: str):
|
24
24
|
"""Fetch user data using an API key.
|
25
25
|
|
26
26
|
Args:
|
27
|
-
|
27
|
+
jwks_url: The JWK URL to use for verification
|
28
28
|
api_key: The API key to verify
|
29
29
|
|
30
30
|
Returns:
|
@@ -34,7 +34,7 @@ def fetch_api_key_data(jwk_url: str, api_key: str):
|
|
34
34
|
USSOException: If the API key is invalid or verification fails
|
35
35
|
"""
|
36
36
|
try:
|
37
|
-
parsed = urlparse(
|
37
|
+
parsed = urlparse(jwks_url)
|
38
38
|
url = f"{parsed.scheme}://{parsed.netloc}/api_key/verify"
|
39
39
|
response = httpx.post(url, json={"api_key": api_key})
|
40
40
|
response.raise_for_status()
|
@@ -0,0 +1,183 @@
|
|
1
|
+
import fnmatch
|
2
|
+
from urllib.parse import parse_qs, urlparse
|
3
|
+
|
4
|
+
PRIVILEGE_LEVELS = {
|
5
|
+
"read": 10,
|
6
|
+
"create": 20,
|
7
|
+
"update": 30,
|
8
|
+
"delete": 40,
|
9
|
+
"manage": 50,
|
10
|
+
"owner": 90,
|
11
|
+
"*": 90,
|
12
|
+
}
|
13
|
+
|
14
|
+
|
15
|
+
def parse_scope(scope: str) -> tuple[str, list[str], dict[str, str]]:
|
16
|
+
"""
|
17
|
+
Parse a scope string into (action, path_parts, filters).
|
18
|
+
|
19
|
+
Examples:
|
20
|
+
"read:media/files/transaction?user_id=123" ->
|
21
|
+
("read", ["media", "files", "transaction"], {"user_id": "123"})
|
22
|
+
|
23
|
+
"media/files/transaction?user_id=123" ->
|
24
|
+
("", ["media", "files", "transaction"], {"user_id": "123"})
|
25
|
+
|
26
|
+
"*:*" ->
|
27
|
+
("*", ["*"], {})
|
28
|
+
|
29
|
+
Returns:
|
30
|
+
- action: str (could be empty string if no scheme present)
|
31
|
+
- path_parts: list[str]
|
32
|
+
- filters: dict[str, str]
|
33
|
+
"""
|
34
|
+
|
35
|
+
parsed = urlparse(scope)
|
36
|
+
path = parsed.path
|
37
|
+
query = parsed.query
|
38
|
+
filters = {k: v[0] for k, v in parse_qs(query).items()}
|
39
|
+
path_parts = path.split("/") if path else ["*"]
|
40
|
+
return parsed.scheme, path_parts, filters
|
41
|
+
|
42
|
+
|
43
|
+
def is_path_match(
|
44
|
+
user_path: list[str] | str,
|
45
|
+
requested_path: list[str] | str,
|
46
|
+
strict: bool = False,
|
47
|
+
) -> bool:
|
48
|
+
"""
|
49
|
+
Match resource paths from right to left, supporting wildcards (*).
|
50
|
+
|
51
|
+
Rules:
|
52
|
+
- The final resource name must match exactly or via fnmatch.
|
53
|
+
- Upper-level path parts are matched from right to left.
|
54
|
+
- Wildcards are allowed in any part.
|
55
|
+
|
56
|
+
Examples = [
|
57
|
+
("files", "files", True),
|
58
|
+
("file-manager/files", "files", True),
|
59
|
+
("media/file-manager/files", "files", True),
|
60
|
+
("media//files", "files", True),
|
61
|
+
("media//files", "file-manager/files", True),
|
62
|
+
("files", "file-manager/files", True),
|
63
|
+
("*/files", "file-manager/files", True),
|
64
|
+
("*//files", "file-manager/files", True),
|
65
|
+
("//files", "file-manager/files", True),
|
66
|
+
("//files", "media/file-manager/files", True),
|
67
|
+
("media//files", "media/file-manager/files", True),
|
68
|
+
("media/files/*", "media/files/transactions", True),
|
69
|
+
("*/*/transactions", "media/files/transactions", True),
|
70
|
+
("media/*/transactions", "media/images/transactions", True),
|
71
|
+
("media//files", "media/files", True), # attention
|
72
|
+
|
73
|
+
("files", "file", False),
|
74
|
+
("files", "files/transactions", False),
|
75
|
+
("files", "media/files/transactions", False),
|
76
|
+
("media/files", "media/files/transactions", False),
|
77
|
+
]
|
78
|
+
"""
|
79
|
+
if isinstance(user_path, str):
|
80
|
+
user_parts = user_path.split("/")
|
81
|
+
elif isinstance(user_path, list):
|
82
|
+
user_parts = user_path
|
83
|
+
else:
|
84
|
+
raise ValueError(f"Invalid path type: {type(user_path)}")
|
85
|
+
|
86
|
+
if isinstance(requested_path, str):
|
87
|
+
req_parts = requested_path.split("/")
|
88
|
+
elif isinstance(requested_path, list):
|
89
|
+
req_parts = requested_path
|
90
|
+
else:
|
91
|
+
raise ValueError(f"Invalid path type: {type(requested_path)}")
|
92
|
+
|
93
|
+
# Match resource name (rightmost)
|
94
|
+
if not fnmatch.fnmatch(req_parts[-1], user_parts[-1]):
|
95
|
+
return False
|
96
|
+
|
97
|
+
# Match rest of the path from right to left
|
98
|
+
user_path_parts = user_parts[:-1]
|
99
|
+
req_path_parts = req_parts[:-1]
|
100
|
+
|
101
|
+
for u, r in zip(
|
102
|
+
reversed(user_path_parts),
|
103
|
+
reversed(req_path_parts),
|
104
|
+
strict=strict,
|
105
|
+
):
|
106
|
+
if r and u and r != "*" and not fnmatch.fnmatch(r, u):
|
107
|
+
return False
|
108
|
+
|
109
|
+
return True
|
110
|
+
|
111
|
+
|
112
|
+
def is_filter_match(user_filters: dict, requested_filters: dict):
|
113
|
+
"""All user filters must match requested filters."""
|
114
|
+
for k, v in user_filters.items():
|
115
|
+
if k not in requested_filters or not fnmatch.fnmatch(
|
116
|
+
str(requested_filters[k]), v
|
117
|
+
):
|
118
|
+
return False
|
119
|
+
return True
|
120
|
+
|
121
|
+
|
122
|
+
def is_authorized(
|
123
|
+
user_scope: str,
|
124
|
+
requested_path: str,
|
125
|
+
requested_action: str | None = None,
|
126
|
+
reuested_filter: dict[str, str] | None = None,
|
127
|
+
*,
|
128
|
+
strict: bool = False,
|
129
|
+
):
|
130
|
+
user_action, user_path, user_filters = parse_scope(user_scope)
|
131
|
+
|
132
|
+
if not is_path_match(user_path, requested_path, strict=strict):
|
133
|
+
return False
|
134
|
+
|
135
|
+
if not is_filter_match(user_filters, reuested_filter):
|
136
|
+
return False
|
137
|
+
|
138
|
+
if requested_action:
|
139
|
+
user_level = PRIVILEGE_LEVELS.get(user_action or "*", 999)
|
140
|
+
req_level = PRIVILEGE_LEVELS.get(requested_action, 0)
|
141
|
+
return user_level >= req_level
|
142
|
+
|
143
|
+
return True
|
144
|
+
|
145
|
+
|
146
|
+
def check_access(
|
147
|
+
user_scopes: list[str],
|
148
|
+
resource_path: str,
|
149
|
+
action: str | None = None,
|
150
|
+
*,
|
151
|
+
filters: list[dict[str, str]] | dict[str, str] | None = None,
|
152
|
+
strict: bool = False,
|
153
|
+
):
|
154
|
+
"""
|
155
|
+
Check if the user has the required access to a resource.
|
156
|
+
|
157
|
+
Args:
|
158
|
+
user_scopes: list of user scope strings
|
159
|
+
resource_path: resource path like "media/files/transactions"
|
160
|
+
action: requested action like "read", "update", etc.
|
161
|
+
filters: optional dict of filters like {"user_id": "abc"}
|
162
|
+
|
163
|
+
Returns:
|
164
|
+
True if access is granted, False otherwise
|
165
|
+
"""
|
166
|
+
if isinstance(filters, dict):
|
167
|
+
filters = [{k: v} for k, v in filters.items()]
|
168
|
+
elif filters is None:
|
169
|
+
filters = ["*"]
|
170
|
+
|
171
|
+
for scope in user_scopes:
|
172
|
+
for filter in filters:
|
173
|
+
if is_authorized(
|
174
|
+
user_scope=scope,
|
175
|
+
requested_path=resource_path,
|
176
|
+
requested_action=action,
|
177
|
+
reuested_filter=filter,
|
178
|
+
strict=strict,
|
179
|
+
):
|
180
|
+
return True
|
181
|
+
print(f"auth failed {filter}, {scope}")
|
182
|
+
|
183
|
+
return False
|
usso/auth/client.py
CHANGED
@@ -70,8 +70,8 @@ class USSOAuthenticationMiddleware(MiddlewareMixin):
|
|
70
70
|
Check if a user exists by phone. If not, create a new user
|
71
71
|
and return it.
|
72
72
|
"""
|
73
|
-
if self.jwt_config.
|
74
|
-
domain = urlparse(self.jwt_config.
|
73
|
+
if self.jwt_config.jwks_url:
|
74
|
+
domain = urlparse(self.jwt_config.jwks_url).netloc
|
75
75
|
else:
|
76
76
|
domain = "example.com"
|
77
77
|
phone = user_data.phone
|
usso/session/async_session.py
CHANGED
@@ -52,11 +52,11 @@ class AsyncUssoSession(httpx.AsyncClient, BaseUssoSession):
|
|
52
52
|
data: dict[str, str | dict[str, str]] = response.json()
|
53
53
|
self.access_token = JWT(
|
54
54
|
token=data.get("access_token"),
|
55
|
-
config=JWTConfig(
|
55
|
+
config=JWTConfig(jwks_url=f"{self.usso_url}/website/jwks.json"),
|
56
56
|
)
|
57
57
|
self._refresh_token = JWT(
|
58
58
|
token=data.get("token", {}).get("refresh_token"),
|
59
|
-
config=JWTConfig(
|
59
|
+
config=JWTConfig(jwks_url=f"{self.usso_url}/website/jwks.json"),
|
60
60
|
)
|
61
61
|
if self.access_token:
|
62
62
|
self.headers.update({
|
usso/session/base_session.py
CHANGED
@@ -48,7 +48,7 @@ class BaseUssoSession:
|
|
48
48
|
self.usso_refresh_url = f"{usso_url}/auth/refresh"
|
49
49
|
self._refresh_token = JWT(
|
50
50
|
token=refresh_token,
|
51
|
-
config=JWTConfig(
|
51
|
+
config=JWTConfig(jwks_url=f"{self.usso_url}/website/jwks.json"),
|
52
52
|
)
|
53
53
|
|
54
54
|
self.access_token = None
|
@@ -67,10 +67,10 @@ class BaseUssoSession:
|
|
67
67
|
def refresh_token(self):
|
68
68
|
if (
|
69
69
|
self._refresh_token
|
70
|
-
and self._refresh_token.verify(
|
70
|
+
and self._refresh_token.verify( # noqa: W503
|
71
71
|
expected_token_type="refresh",
|
72
72
|
)
|
73
|
-
and self._refresh_token.is_temporally_valid()
|
73
|
+
and self._refresh_token.is_temporally_valid() # noqa: W503
|
74
74
|
):
|
75
75
|
self._refresh_token = None
|
76
76
|
|
usso/session/session.py
CHANGED
@@ -38,7 +38,7 @@ class UssoSession(httpx.Client, BaseUssoSession):
|
|
38
38
|
response.raise_for_status()
|
39
39
|
self.access_token = JWT(
|
40
40
|
token=response.json().get("access_token"),
|
41
|
-
config=JWTConfig(
|
41
|
+
config=JWTConfig(jwks_url=f"{self.usso_url}/website/jwks.json"),
|
42
42
|
)
|
43
43
|
self.headers.update({"Authorization": f"Bearer {self.access_token}"})
|
44
44
|
return response.json()
|
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: usso
|
3
|
-
Version: 0.28.
|
3
|
+
Version: 0.28.16
|
4
4
|
Summary: A plug-and-play client for integrating universal single sign-on (SSO) with Python frameworks, enabling secure and seamless authentication across microservices.
|
5
5
|
Author-email: Mahdi Kiani <mahdikiany@gmail.com>
|
6
6
|
Maintainer-email: Mahdi Kiani <mahdikiany@gmail.com>
|
@@ -28,7 +28,7 @@ Requires-Dist: cachetools
|
|
28
28
|
Requires-Dist: singleton_package
|
29
29
|
Requires-Dist: json-advanced
|
30
30
|
Requires-Dist: httpx
|
31
|
-
Requires-Dist: usso-jwt>=0.
|
31
|
+
Requires-Dist: usso-jwt>=0.2.0
|
32
32
|
Provides-Extra: fastapi
|
33
33
|
Requires-Dist: fastapi>=0.65.0; extra == "fastapi"
|
34
34
|
Requires-Dist: uvicorn[standard]>=0.13.0; extra == "fastapi"
|
@@ -148,7 +148,7 @@ Then configure your app to verify tokens issued by this service, using its publi
|
|
148
148
|
|
149
149
|
```python
|
150
150
|
JWTConfig(
|
151
|
-
|
151
|
+
jwks_url="http://localhost:8000/.well-known/jwks.json",
|
152
152
|
...
|
153
153
|
)
|
154
154
|
```
|
@@ -1,25 +1,26 @@
|
|
1
1
|
usso/__init__.py,sha256=t3tYcw4qtGFpk7iakXTqEj5RlzIc8D2fs0I3FZcOmGs,571
|
2
2
|
usso/exceptions.py,sha256=cBzmMCwpNQKMjCUXO3bCcFwZJQQvbvJ5RxTH987ZlCI,1012
|
3
3
|
usso/auth/__init__.py,sha256=Dthv-iZTgsHTGcJrkJsnAtDCbRR5dNCx0Ut7MufoAXY,270
|
4
|
-
usso/auth/api_key.py,sha256=
|
5
|
-
usso/auth/
|
4
|
+
usso/auth/api_key.py,sha256=cT0ZCMhr8mX3-tByocvhOmK0kkeFCMMGtd6cZdzIspA,1257
|
5
|
+
usso/auth/authorization.py,sha256=HuNBgz0RSPMevPAhZdqsCpp-Uz1MrDM37KvC5utVwqU,5489
|
6
|
+
usso/auth/client.py,sha256=BD4auDPCLoIPHIg8_JXjqFkc2a_6QrAxDkYjoB4416Q,2588
|
6
7
|
usso/auth/config.py,sha256=wRMsR89tw_PbUY83ObuEMCWuj3_Y8gcuYj8yZ-PiDFs,3739
|
7
8
|
usso/integrations/django/__init__.py,sha256=dKpbffHS5ouGtW6ooI2ivzjPmH_1rOBny85htR-KqrY,97
|
8
|
-
usso/integrations/django/middleware.py,sha256=
|
9
|
+
usso/integrations/django/middleware.py,sha256=AZKYZ4UPNmyxcD3ANgp0y_fdrFvVQdHBqyYxo5XhQUs,3445
|
9
10
|
usso/integrations/fastapi/__init__.py,sha256=ohToiqutHu3Okr8naunssDkamj1OdiG4OpPdBW0rt7U,204
|
10
11
|
usso/integrations/fastapi/dependency.py,sha256=Cq-rkCrmNIC8OT1OkdMxfIEkmQkl_pwqV7N7CiNnDSA,2801
|
11
12
|
usso/integrations/fastapi/handler.py,sha256=MNDoBYdySumFsBgVw-xir3jXXH63KehFXKCh-pNnNZQ,386
|
12
13
|
usso/models/user.py,sha256=eVZD1roaXkHiyO_fmMVoIAoE8AVvot4RTySJcYMe2uw,3760
|
13
14
|
usso/session/__init__.py,sha256=tE4qWUdSI7iN_pywm47Mg8NKOTBa2nCNwCy3wCZWRmU,124
|
14
|
-
usso/session/async_session.py,sha256=
|
15
|
-
usso/session/base_session.py,sha256=
|
16
|
-
usso/session/session.py,sha256=
|
15
|
+
usso/session/async_session.py,sha256=eQQh2DXiaHdballRjePa8GSI9GmGsxNDU7vTfwh8mRQ,3971
|
16
|
+
usso/session/base_session.py,sha256=O3tEltMhlwkEz1GGbjE4iXPwSlLaUW2juUt9RDSLrHI,2559
|
17
|
+
usso/session/session.py,sha256=briCgDMoF-b59H6Aie_Lmjy4qnPBBSmKnVhAwef34F0,1637
|
17
18
|
usso/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
18
19
|
usso/utils/method_utils.py,sha256=1NMN4le04PWXDSJZK-nf7q2IFqOMkwYcCnslFXAzlH8,355
|
19
20
|
usso/utils/string_utils.py,sha256=7tziAa2Cwa7xhwM_NF4DSY3BHoqVaWgJ21VuV8LvhrY,253
|
20
|
-
usso-0.28.
|
21
|
-
usso-0.28.
|
22
|
-
usso-0.28.
|
23
|
-
usso-0.28.
|
24
|
-
usso-0.28.
|
25
|
-
usso-0.28.
|
21
|
+
usso-0.28.16.dist-info/licenses/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
|
22
|
+
usso-0.28.16.dist-info/METADATA,sha256=CwuJO02M13iJKbJc28gQ69WoJOFoz7MJS3aW8rTd0nQ,5061
|
23
|
+
usso-0.28.16.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
24
|
+
usso-0.28.16.dist-info/entry_points.txt,sha256=4Zgpm5ELaAWPf0jPGJFz1_X69H7un8ycT3WdGoJ0Vvk,35
|
25
|
+
usso-0.28.16.dist-info/top_level.txt,sha256=g9Jf6h1Oyidh0vPiFni7UHInTJjSvu6cUalpLTIvthg,5
|
26
|
+
usso-0.28.16.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|