forked from workos/workos-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.py
More file actions
360 lines (309 loc) · 12.9 KB
/
session.py
File metadata and controls
360 lines (309 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
from __future__ import annotations
from typing import TYPE_CHECKING, List, Protocol
from functools import lru_cache
import json
from typing import Any, Dict, Optional, Union, cast
import jwt
from jwt import PyJWKClient
from cryptography.fernet import Fernet
from workos.types.user_management.session import (
AuthenticateWithSessionCookieFailureReason,
AuthenticateWithSessionCookieSuccessResponse,
AuthenticateWithSessionCookieErrorResponse,
RefreshWithSessionCookieErrorResponse,
RefreshWithSessionCookieSuccessResponse,
)
from workos.typing.sync_or_async import SyncOrAsync
if TYPE_CHECKING:
from workos.user_management import UserManagementModule
from workos.user_management import AsyncUserManagement, UserManagement
@lru_cache(maxsize=None)
def _get_jwks_client(jwks_url: str) -> PyJWKClient:
return PyJWKClient(jwks_url)
class SessionModule(Protocol):
user_management: "UserManagementModule"
client_id: str
session_data: str
cookie_password: str
jwks: PyJWKClient
jwk_algorithms: List[str]
jwt_leeway: float
def __init__(
self,
*,
user_management: "UserManagementModule",
client_id: str,
session_data: str,
cookie_password: str,
jwt_leeway: float = 0,
) -> None:
# If the cookie password is not provided, throw an error
if cookie_password is None or cookie_password == "":
raise ValueError("cookie_password is required")
self.user_management = user_management
self.client_id = client_id
self.session_data = session_data
self.cookie_password = cookie_password
self.jwt_leeway = jwt_leeway
self.jwks = _get_jwks_client(self.user_management.get_jwks_url())
# Algorithms are hardcoded for security reasons. See https://pyjwt.readthedocs.io/en/stable/algorithms.html#specifying-an-algorithm
self.jwk_algorithms = ["RS256"]
def authenticate(
self,
) -> Union[
AuthenticateWithSessionCookieSuccessResponse,
AuthenticateWithSessionCookieErrorResponse,
]:
if self.session_data is None or self.session_data == "":
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.NO_SESSION_COOKIE_PROVIDED,
)
try:
session = self.unseal_data(self.session_data, self.cookie_password)
except Exception:
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)
if not session.get("access_token", None):
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)
try:
signing_key = self.jwks.get_signing_key_from_jwt(session["access_token"])
decoded = jwt.decode(
session["access_token"],
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
leeway=self.jwt_leeway,
)
except jwt.exceptions.InvalidTokenError:
return AuthenticateWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
)
return AuthenticateWithSessionCookieSuccessResponse(
authenticated=True,
session_id=decoded["sid"],
organization_id=decoded.get("org_id", None),
role=decoded.get("role", None),
roles=decoded.get("roles", None),
permissions=decoded.get("permissions", None),
entitlements=decoded.get("entitlements", None),
user=session["user"],
impersonator=session.get("impersonator", None),
feature_flags=decoded.get("feature_flags", None),
)
def refresh(
self,
*,
organization_id: Optional[str] = None,
cookie_password: Optional[str] = None,
) -> SyncOrAsync[
Union[
RefreshWithSessionCookieSuccessResponse,
RefreshWithSessionCookieErrorResponse,
]
]: ...
def get_logout_url(self, return_to: Optional[str] = None) -> str:
auth_response = self.authenticate()
if isinstance(auth_response, AuthenticateWithSessionCookieErrorResponse):
raise ValueError(
f"Failed to extract session ID for logout URL: {auth_response.reason}"
)
result = self.user_management.get_logout_url(
session_id=auth_response.session_id,
return_to=return_to,
)
return str(result)
def _is_valid_jwt(self, token: str) -> bool:
try:
signing_key = self.jwks.get_signing_key_from_jwt(token)
jwt.decode(
token,
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
leeway=self.jwt_leeway,
)
return True
except jwt.exceptions.InvalidTokenError:
return False
@staticmethod
def seal_data(data: Dict[str, Any], key: str) -> str:
fernet = Fernet(key)
# Encrypt and convert bytes to string
encrypted_bytes = fernet.encrypt(json.dumps(data).encode())
return encrypted_bytes.decode("utf-8")
@staticmethod
def unseal_data(sealed_data: str, key: str) -> Dict[str, Any]:
fernet = Fernet(key)
# Convert string back to bytes before decryption
encrypted_bytes = sealed_data.encode("utf-8")
decrypted_str = fernet.decrypt(encrypted_bytes).decode()
return cast(Dict[str, Any], json.loads(decrypted_str))
class Session(SessionModule):
user_management: "UserManagement"
def __init__(
self,
*,
user_management: "UserManagement",
client_id: str,
session_data: str,
cookie_password: str,
jwt_leeway: float = 0,
) -> None:
# If the cookie password is not provided, throw an error
if cookie_password is None or cookie_password == "":
raise ValueError("cookie_password is required")
self.user_management = user_management
self.client_id = client_id
self.session_data = session_data
self.cookie_password = cookie_password
self.jwt_leeway = jwt_leeway
self.jwks = _get_jwks_client(self.user_management.get_jwks_url())
# Algorithms are hardcoded for security reasons. See https://pyjwt.readthedocs.io/en/stable/algorithms.html#specifying-an-algorithm
self.jwk_algorithms = ["RS256"]
def refresh(
self,
*,
organization_id: Optional[str] = None,
cookie_password: Optional[str] = None,
) -> Union[
RefreshWithSessionCookieSuccessResponse,
RefreshWithSessionCookieErrorResponse,
]:
cookie_password = (
self.cookie_password if cookie_password is None else cookie_password
)
try:
session = self.unseal_data(self.session_data, cookie_password)
except Exception:
return RefreshWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)
if not session.get("refresh_token", None) or not session.get("user", None):
return RefreshWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)
try:
auth_response = self.user_management.authenticate_with_refresh_token(
refresh_token=session["refresh_token"],
organization_id=organization_id,
session={"seal_session": True, "cookie_password": cookie_password},
)
self.session_data = str(auth_response.sealed_session)
self.cookie_password = (
cookie_password if cookie_password is not None else self.cookie_password
)
signing_key = self.jwks.get_signing_key_from_jwt(auth_response.access_token)
decoded = jwt.decode(
auth_response.access_token,
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
leeway=self.jwt_leeway,
)
return RefreshWithSessionCookieSuccessResponse(
authenticated=True,
sealed_session=str(auth_response.sealed_session),
session_id=decoded["sid"],
organization_id=decoded.get("org_id", None),
role=decoded.get("role", None),
roles=decoded.get("roles", None),
permissions=decoded.get("permissions", None),
entitlements=decoded.get("entitlements", None),
user=auth_response.user,
impersonator=auth_response.impersonator,
feature_flags=decoded.get("feature_flags", None),
)
except Exception as e:
return RefreshWithSessionCookieErrorResponse(
authenticated=False, reason=str(e)
)
class AsyncSession(SessionModule):
user_management: "AsyncUserManagement"
def __init__(
self,
*,
user_management: "AsyncUserManagement",
client_id: str,
session_data: str,
cookie_password: str,
jwt_leeway: float = 0,
) -> None:
# If the cookie password is not provided, throw an error
if cookie_password is None or cookie_password == "":
raise ValueError("cookie_password is required")
self.user_management = user_management
self.client_id = client_id
self.session_data = session_data
self.cookie_password = cookie_password
self.jwt_leeway = jwt_leeway
self.jwks = _get_jwks_client(self.user_management.get_jwks_url())
# Algorithms are hardcoded for security reasons. See https://pyjwt.readthedocs.io/en/stable/algorithms.html#specifying-an-algorithm
self.jwk_algorithms = ["RS256"]
async def refresh(
self,
*,
organization_id: Optional[str] = None,
cookie_password: Optional[str] = None,
) -> Union[
RefreshWithSessionCookieSuccessResponse,
RefreshWithSessionCookieErrorResponse,
]:
cookie_password = (
self.cookie_password if cookie_password is None else cookie_password
)
try:
session = self.unseal_data(self.session_data, cookie_password)
except Exception:
return RefreshWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)
if not session.get("refresh_token", None) or not session.get("user", None):
return RefreshWithSessionCookieErrorResponse(
authenticated=False,
reason=AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE,
)
try:
auth_response = await self.user_management.authenticate_with_refresh_token(
refresh_token=session["refresh_token"],
organization_id=organization_id,
session={"seal_session": True, "cookie_password": cookie_password},
)
self.session_data = str(auth_response.sealed_session)
self.cookie_password = (
cookie_password if cookie_password is not None else self.cookie_password
)
signing_key = self.jwks.get_signing_key_from_jwt(auth_response.access_token)
decoded = jwt.decode(
auth_response.access_token,
signing_key.key,
algorithms=self.jwk_algorithms,
options={"verify_aud": False},
leeway=self.jwt_leeway,
)
return RefreshWithSessionCookieSuccessResponse(
authenticated=True,
sealed_session=str(auth_response.sealed_session),
session_id=decoded["sid"],
organization_id=decoded.get("org_id", None),
role=decoded.get("role", None),
roles=decoded.get("roles", None),
permissions=decoded.get("permissions", None),
entitlements=decoded.get("entitlements", None),
user=auth_response.user,
impersonator=auth_response.impersonator,
feature_flags=decoded.get("feature_flags", None),
)
except Exception as e:
return RefreshWithSessionCookieErrorResponse(
authenticated=False, reason=str(e)
)