usso 0.28.15__tar.gz → 0.28.17__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.
Files changed (35) hide show
  1. {usso-0.28.15/src/usso.egg-info → usso-0.28.17}/PKG-INFO +1 -1
  2. {usso-0.28.15 → usso-0.28.17}/pyproject.toml +1 -1
  3. {usso-0.28.15 → usso-0.28.17}/src/usso/auth/api_key.py +4 -7
  4. usso-0.28.17/src/usso/auth/authorization.py +183 -0
  5. {usso-0.28.15 → usso-0.28.17}/src/usso/auth/client.py +4 -1
  6. {usso-0.28.15 → usso-0.28.17}/src/usso/auth/config.py +1 -1
  7. {usso-0.28.15 → usso-0.28.17/src/usso.egg-info}/PKG-INFO +1 -1
  8. {usso-0.28.15 → usso-0.28.17}/src/usso.egg-info/SOURCES.txt +2 -0
  9. usso-0.28.17/tests/test_authorization.py +167 -0
  10. {usso-0.28.15 → usso-0.28.17}/LICENSE.txt +0 -0
  11. {usso-0.28.15 → usso-0.28.17}/MANIFEST.in +0 -0
  12. {usso-0.28.15 → usso-0.28.17}/README.md +0 -0
  13. {usso-0.28.15 → usso-0.28.17}/pytest.ini +0 -0
  14. {usso-0.28.15 → usso-0.28.17}/setup.cfg +0 -0
  15. {usso-0.28.15 → usso-0.28.17}/src/usso/__init__.py +0 -0
  16. {usso-0.28.15 → usso-0.28.17}/src/usso/auth/__init__.py +0 -0
  17. {usso-0.28.15 → usso-0.28.17}/src/usso/exceptions.py +0 -0
  18. {usso-0.28.15 → usso-0.28.17}/src/usso/integrations/django/__init__.py +0 -0
  19. {usso-0.28.15 → usso-0.28.17}/src/usso/integrations/django/middleware.py +0 -0
  20. {usso-0.28.15 → usso-0.28.17}/src/usso/integrations/fastapi/__init__.py +0 -0
  21. {usso-0.28.15 → usso-0.28.17}/src/usso/integrations/fastapi/dependency.py +0 -0
  22. {usso-0.28.15 → usso-0.28.17}/src/usso/integrations/fastapi/handler.py +0 -0
  23. {usso-0.28.15 → usso-0.28.17}/src/usso/models/user.py +0 -0
  24. {usso-0.28.15 → usso-0.28.17}/src/usso/session/__init__.py +0 -0
  25. {usso-0.28.15 → usso-0.28.17}/src/usso/session/async_session.py +0 -0
  26. {usso-0.28.15 → usso-0.28.17}/src/usso/session/base_session.py +0 -0
  27. {usso-0.28.15 → usso-0.28.17}/src/usso/session/session.py +0 -0
  28. {usso-0.28.15 → usso-0.28.17}/src/usso/utils/__init__.py +0 -0
  29. {usso-0.28.15 → usso-0.28.17}/src/usso/utils/method_utils.py +0 -0
  30. {usso-0.28.15 → usso-0.28.17}/src/usso/utils/string_utils.py +0 -0
  31. {usso-0.28.15 → usso-0.28.17}/src/usso.egg-info/dependency_links.txt +0 -0
  32. {usso-0.28.15 → usso-0.28.17}/src/usso.egg-info/entry_points.txt +0 -0
  33. {usso-0.28.15 → usso-0.28.17}/src/usso.egg-info/requires.txt +0 -0
  34. {usso-0.28.15 → usso-0.28.17}/src/usso.egg-info/top_level.txt +0 -0
  35. {usso-0.28.15 → usso-0.28.17}/tests/test_fastapi.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: usso
3
- Version: 0.28.15
3
+ Version: 0.28.17
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>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "usso"
7
- version = "0.28.15"
7
+ version = "0.28.17"
8
8
  description = "A plug-and-play client for integrating universal single sign-on (SSO) with Python frameworks, enabling secure and seamless authentication across microservices."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,5 +1,4 @@
1
1
  import logging
2
- from urllib.parse import urlparse
3
2
 
4
3
  import cachetools.func
5
4
  import httpx
@@ -19,12 +18,12 @@ def _handle_exception(error_type: str, **kwargs):
19
18
  logger.error(kwargs.get("message") or error_type)
20
19
 
21
20
 
22
- @cachetools.func.ttl_cache(maxsize=128, ttl=10 * 60)
23
- def fetch_api_key_data(jwks_url: str, api_key: str):
21
+ @cachetools.func.ttl_cache(maxsize=128, ttl=60)
22
+ def fetch_api_key_data(api_key_verify_url: str, api_key: str):
24
23
  """Fetch user data using an API key.
25
24
 
26
25
  Args:
27
- jwks_url: The JWK URL to use for verification
26
+ api_key_verify_url: The API key verify URL to use for verification
28
27
  api_key: The API key to verify
29
28
 
30
29
  Returns:
@@ -34,9 +33,7 @@ def fetch_api_key_data(jwks_url: str, api_key: str):
34
33
  USSOException: If the API key is invalid or verification fails
35
34
  """
36
35
  try:
37
- parsed = urlparse(jwks_url)
38
- url = f"{parsed.scheme}://{parsed.netloc}/api_key/verify"
39
- response = httpx.post(url, json={"api_key": api_key})
36
+ response = httpx.post(api_key_verify_url, json={"api_key": api_key})
40
37
  response.raise_for_status()
41
38
  return UserData(**response.json())
42
39
  except Exception as e:
@@ -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
@@ -87,4 +87,7 @@ class UssoAuth:
87
87
  Raises:
88
88
  USSOException: If the API key is invalid
89
89
  """
90
- return fetch_api_key_data(self.jwt_configs[0].jwks_url, api_key)
90
+ return fetch_api_key_data(
91
+ self.jwt_configs[0].api_key_header.verify_endpoint,
92
+ api_key,
93
+ )
@@ -42,7 +42,7 @@ class HeaderConfig(BaseModel):
42
42
 
43
43
 
44
44
  class APIHeaderConfig(HeaderConfig):
45
- verify_endpoint: str = "https://sso.usso.io/api_key/verify"
45
+ verify_endpoint: str = "https://sso.usso.io/api/sso/v1/apikeys/verify"
46
46
 
47
47
 
48
48
  class AuthConfig(usso_jwt.config.JWTConfig):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: usso
3
- Version: 0.28.15
3
+ Version: 0.28.17
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>
@@ -13,6 +13,7 @@ src/usso.egg-info/requires.txt
13
13
  src/usso.egg-info/top_level.txt
14
14
  src/usso/auth/__init__.py
15
15
  src/usso/auth/api_key.py
16
+ src/usso/auth/authorization.py
16
17
  src/usso/auth/client.py
17
18
  src/usso/auth/config.py
18
19
  src/usso/integrations/django/__init__.py
@@ -28,4 +29,5 @@ src/usso/session/session.py
28
29
  src/usso/utils/__init__.py
29
30
  src/usso/utils/method_utils.py
30
31
  src/usso/utils/string_utils.py
32
+ tests/test_authorization.py
31
33
  tests/test_fastapi.py
@@ -0,0 +1,167 @@
1
+ import pytest
2
+
3
+ from src.usso.auth.authorization import check_access, is_path_match
4
+
5
+
6
+ @pytest.mark.parametrize(
7
+ "user_path, requested_path, expected",
8
+ [
9
+ ("files", "files", True),
10
+ ("file-manager/files", "files", True),
11
+ ("media/file-manager/files", "files", True),
12
+ ("media//files", "files", True),
13
+ ("media//files", "file-manager/files", True),
14
+ ("files", "file-manager/files", True),
15
+ ("*/files", "file-manager/files", True),
16
+ ("*//files", "file-manager/files", True),
17
+ ("//files", "file-manager/files", True),
18
+ ("//files", "media/file-manager/files", True),
19
+ ("media//files", "media/file-manager/files", True),
20
+ (
21
+ "media//files",
22
+ "media/files",
23
+ True,
24
+ ), # !! atention it matches because the middle part is empty
25
+ ("media/files/*", "media/files/transactions", True),
26
+ ("*/*/transactions", "media/files/transactions", True),
27
+ ("media/*/transactions", "media/images/transactions", True),
28
+ ("files", "file", False),
29
+ ("files", "files/transactions", False),
30
+ ("files", "media/files/transactions", False),
31
+ ("media/files", "media/files/transactions", False),
32
+ ],
33
+ )
34
+ def test_path_match(user_path, requested_path, expected):
35
+ assert is_path_match(user_path, requested_path, strict=False) == expected
36
+
37
+
38
+ # Define pytest tests
39
+ def test_exact_match_id():
40
+ scopes = ["read:media/file-manager/files?uid=file123"]
41
+ assert (
42
+ check_access(
43
+ scopes,
44
+ "files",
45
+ action="read",
46
+ filters=[
47
+ dict(namespace="media"),
48
+ dict(service="file-manager"),
49
+ dict(uid="file123"),
50
+ ],
51
+ )
52
+ is True
53
+ )
54
+
55
+
56
+ # Define pytest tests
57
+ def test_wildcard():
58
+ scopes = [
59
+ "update:media/files/transactions?user_id=abc",
60
+ "read:media/files/*",
61
+ ]
62
+
63
+ assert check_access(
64
+ scopes,
65
+ "media/files/transactions",
66
+ action="read",
67
+ filters={"user_id": "abc"},
68
+ )
69
+ assert check_access(
70
+ scopes, "transactions", action="update", filters={"user_id": "abc"}
71
+ )
72
+ assert not check_access(
73
+ scopes, "transactions", action="update", filters={"uid": "def"}
74
+ )
75
+ assert not check_access(
76
+ scopes,
77
+ "media/files/transactions",
78
+ action="delete",
79
+ filters={"user_id": "abc"},
80
+ )
81
+
82
+
83
+ def test_insufficient_privilege():
84
+ scopes = ["read:media/files/file:uid:file123"]
85
+ assert (
86
+ check_access(
87
+ scopes,
88
+ "file",
89
+ "update",
90
+ filters=[
91
+ dict(namespace="finance"),
92
+ dict(service="wallet"),
93
+ dict(workspace_id="ws_7"),
94
+ ],
95
+ )
96
+ is False
97
+ )
98
+
99
+
100
+ def test_wildcard_match():
101
+ scopes = ["manage:media/files/file?*"]
102
+ assert (
103
+ check_access(
104
+ scopes,
105
+ "file",
106
+ "update",
107
+ filters=dict(
108
+ namespace="finance",
109
+ service="wallet",
110
+ workspace_id="ws_7",
111
+ ),
112
+ )
113
+ is True
114
+ )
115
+
116
+
117
+ def test_match_by_user_id():
118
+ scopes = ["manage:finance/wallet/transaction?user=user_1"]
119
+ assert (
120
+ check_access(
121
+ scopes,
122
+ "transaction",
123
+ "update",
124
+ filters=[
125
+ dict(namespace="finance"),
126
+ dict(service="wallet"),
127
+ dict(workspace_id="ws_7"),
128
+ ],
129
+ )
130
+ is False
131
+ )
132
+ assert (
133
+ check_access(
134
+ scopes,
135
+ "transaction",
136
+ "update",
137
+ filters=dict(namespace="finance", user="user_1"),
138
+ )
139
+ is True
140
+ )
141
+
142
+
143
+ def test_match_by_workspace_id():
144
+ scopes = ["delete:finance/wallet/transaction?workspace_id=ws_7"]
145
+ assert (
146
+ check_access(
147
+ scopes,
148
+ "transaction",
149
+ "delete",
150
+ filters=[
151
+ dict(namespace="finance"),
152
+ dict(service="wallet"),
153
+ dict(workspace_id="ws_7"),
154
+ ],
155
+ )
156
+ is True
157
+ )
158
+
159
+
160
+ def test_minimal_params_success():
161
+ scopes = ["create:file?*"]
162
+ assert check_access(scopes, "file", "create") is True
163
+
164
+
165
+ def test_minimal_params_fail():
166
+ scopes = ["read:file?*"]
167
+ assert check_access(scopes, "file", "create") is False
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes