usso 0.28.15__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.
@@ -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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: usso
3
- Version: 0.28.15
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>
@@ -2,6 +2,7 @@ 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
4
  usso/auth/api_key.py,sha256=cT0ZCMhr8mX3-tByocvhOmK0kkeFCMMGtd6cZdzIspA,1257
5
+ usso/auth/authorization.py,sha256=HuNBgz0RSPMevPAhZdqsCpp-Uz1MrDM37KvC5utVwqU,5489
5
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
@@ -17,9 +18,9 @@ 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.15.dist-info/licenses/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
21
- usso-0.28.15.dist-info/METADATA,sha256=bo-q8BYf5QBtR7VgHQEzZgEWwi9GytazA3TcqMfsfjU,5061
22
- usso-0.28.15.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
23
- usso-0.28.15.dist-info/entry_points.txt,sha256=4Zgpm5ELaAWPf0jPGJFz1_X69H7un8ycT3WdGoJ0Vvk,35
24
- usso-0.28.15.dist-info/top_level.txt,sha256=g9Jf6h1Oyidh0vPiFni7UHInTJjSvu6cUalpLTIvthg,5
25
- usso-0.28.15.dist-info/RECORD,,
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