-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtest_session.py
497 lines (427 loc) · 17.5 KB
/
test_session.py
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import pytest
from unittest.mock import AsyncMock, Mock, patch
import jwt
from datetime import datetime, timezone
from tests.conftest import with_jwks_mock
from workos.session import AsyncSession, Session
from workos.types.user_management.authentication_response import (
RefreshTokenAuthenticationResponse,
)
from workos.types.user_management.session import (
AuthenticateWithSessionCookieFailureReason,
AuthenticateWithSessionCookieSuccessResponse,
RefreshWithSessionCookieErrorResponse,
RefreshWithSessionCookieSuccessResponse,
)
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
class SessionFixtures:
@pytest.fixture
def session_constants(self):
# Generate RSA key pair for testing
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# Get the private key in PEM format
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
current_datetime = datetime.now(timezone.utc)
current_timestamp = str(current_datetime)
token_claims = {
"sid": "session_123",
"org_id": "organization_123",
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
"exp": int(current_datetime.timestamp()) + 3600,
"iat": int(current_datetime.timestamp()),
}
user_id = "user_123"
return {
"COOKIE_PASSWORD": "pfSqwTFXUTGEBBD1RQh2kt/oNJYxBgaoZan4Z8sMrKU=",
"SESSION_DATA": "session_data",
"CLIENT_ID": "client_123",
"USER_ID": user_id,
"SESSION_ID": "session_123",
"ORGANIZATION_ID": "organization_123",
"CURRENT_DATETIME": current_datetime,
"CURRENT_TIMESTAMP": current_timestamp,
"PRIVATE_KEY": private_pem,
"PUBLIC_KEY": public_key,
"TEST_TOKEN": jwt.encode(token_claims, private_pem, algorithm="RS256"),
"TEST_TOKEN_CLAIMS": token_claims,
"TEST_USER": {
"object": "user",
"id": user_id,
"email": "user@example.com",
"first_name": "Test",
"last_name": "User",
"email_verified": True,
"created_at": current_timestamp,
"updated_at": current_timestamp,
},
}
@pytest.fixture
def mock_user_management(self):
mock = Mock()
mock.get_jwks_url.return_value = (
"https://api.workos.com/user_management/sso/jwks/client_123"
)
return mock
class TestSessionBase(SessionFixtures):
@with_jwks_mock
def test_initialize_session_module(self, session_constants, mock_user_management):
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_constants["SESSION_DATA"],
cookie_password=session_constants["COOKIE_PASSWORD"],
)
assert session.client_id == session_constants["CLIENT_ID"]
assert session.cookie_password is not None
@with_jwks_mock
def test_initialize_without_cookie_password(
self, session_constants, mock_user_management
):
with pytest.raises(ValueError, match="cookie_password is required"):
Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_constants["SESSION_DATA"],
cookie_password="",
)
@with_jwks_mock
def test_authenticate_no_session_cookie_provided(
self, session_constants, mock_user_management
):
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data="",
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = session.authenticate()
assert response.authenticated is False
assert (
response.reason
== AuthenticateWithSessionCookieFailureReason.NO_SESSION_COOKIE_PROVIDED
)
@with_jwks_mock
def test_authenticate_invalid_session_cookie(
self, session_constants, mock_user_management
):
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data="invalid_session_data",
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = session.authenticate()
assert response.authenticated is False
assert (
response.reason
== AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE
)
@with_jwks_mock
def test_authenticate_invalid_jwt(self, session_constants, mock_user_management):
invalid_session_data = Session.seal_data(
{"access_token": "invalid_session_data"},
session_constants["COOKIE_PASSWORD"],
)
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=invalid_session_data,
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = session.authenticate()
assert response.authenticated is False
assert response.reason == AuthenticateWithSessionCookieFailureReason.INVALID_JWT
@with_jwks_mock
def test_authenticate_jwt_with_aud_claim(
self, session_constants, mock_user_management
):
access_token = jwt.encode(
{
**session_constants["TEST_TOKEN_CLAIMS"],
**{"aud": session_constants["CLIENT_ID"]},
},
session_constants["PRIVATE_KEY"],
algorithm="RS256",
)
session_data = Session.seal_data(
{"access_token": access_token, "user": session_constants["TEST_USER"]},
session_constants["COOKIE_PASSWORD"],
)
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_data,
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = session.authenticate()
assert isinstance(response, AuthenticateWithSessionCookieSuccessResponse)
@with_jwks_mock
def test_authenticate_success(self, session_constants, mock_user_management):
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_constants["SESSION_DATA"],
cookie_password=session_constants["COOKIE_PASSWORD"],
)
# Mock the session data that would be unsealed
mock_session = {
"access_token": jwt.encode(
{
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
"exp": int(datetime.now(timezone.utc).timestamp()) + 3600,
"iat": int(datetime.now(timezone.utc).timestamp()),
},
session_constants["PRIVATE_KEY"],
algorithm="RS256",
),
"user": {
"object": "user",
"id": session_constants["USER_ID"],
"email": "user@example.com",
"email_verified": True,
"created_at": session_constants["CURRENT_TIMESTAMP"],
"updated_at": session_constants["CURRENT_TIMESTAMP"],
},
"impersonator": None,
}
# Mock the JWT payload that would be decoded
mock_jwt_payload = {
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
}
with patch.object(
Session, "unseal_data", return_value=mock_session
), patch.object(session, "_is_valid_jwt", return_value=True), patch(
"jwt.decode", return_value=mock_jwt_payload
), patch.object(
session.jwks,
"get_signing_key_from_jwt",
return_value=Mock(key=session_constants["PUBLIC_KEY"]),
):
response = session.authenticate()
assert isinstance(response, AuthenticateWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.session_id == session_constants["SESSION_ID"]
assert response.organization_id == session_constants["ORGANIZATION_ID"]
assert response.role == "admin"
assert response.permissions == ["read"]
assert response.entitlements == ["feature_1"]
assert response.user.id == session_constants["USER_ID"]
assert response.impersonator is None
@with_jwks_mock
def test_refresh_invalid_session_cookie(
self, session_constants, mock_user_management
):
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data="invalid_session_data",
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = session.refresh()
assert isinstance(response, RefreshWithSessionCookieErrorResponse)
assert (
response.reason
== AuthenticateWithSessionCookieFailureReason.INVALID_SESSION_COOKIE
)
def test_seal_data(self, session_constants):
test_data = {"test": "data"}
sealed = Session.seal_data(test_data, session_constants["COOKIE_PASSWORD"])
assert isinstance(sealed, str)
# Test unsealing
unsealed = Session.unseal_data(sealed, session_constants["COOKIE_PASSWORD"])
assert unsealed == test_data
def test_unseal_invalid_data(self, session_constants):
with pytest.raises(
Exception
): # Adjust exception type based on your implementation
Session.unseal_data(
"invalid_sealed_data", session_constants["COOKIE_PASSWORD"]
)
class TestSession(SessionFixtures):
@with_jwks_mock
def test_refresh_success(self, session_constants, mock_user_management):
session_data = Session.seal_data(
{
"refresh_token": "refresh_token_12345",
"user": session_constants["TEST_USER"],
},
session_constants["COOKIE_PASSWORD"],
)
mock_response = {
"access_token": session_constants["TEST_TOKEN"],
"refresh_token": "refresh_token_123",
"sealed_session": session_data,
"user": session_constants["TEST_USER"],
}
mock_user_management.authenticate_with_refresh_token.return_value = (
RefreshTokenAuthenticationResponse(**mock_response)
)
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_data,
cookie_password=session_constants["COOKIE_PASSWORD"],
)
with patch.object(session, "_is_valid_jwt", return_value=True) as _:
with patch(
"jwt.decode",
return_value={
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
},
):
response = session.refresh()
assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.user.id == session_constants["TEST_USER"]["id"]
# Verify the refresh token was used correctly
mock_user_management.authenticate_with_refresh_token.assert_called_once_with(
refresh_token="refresh_token_12345",
organization_id=None,
session={
"seal_session": True,
"cookie_password": session_constants["COOKIE_PASSWORD"],
},
)
@with_jwks_mock
def test_refresh_success_with_aud_claim(
self, session_constants, mock_user_management
):
session_data = Session.seal_data(
{
"refresh_token": "refresh_token_12345",
"user": session_constants["TEST_USER"],
},
session_constants["COOKIE_PASSWORD"],
)
access_token = jwt.encode(
{
**session_constants["TEST_TOKEN_CLAIMS"],
**{"aud": session_constants["CLIENT_ID"]},
},
session_constants["PRIVATE_KEY"],
algorithm="RS256",
)
mock_response = {
"access_token": access_token,
"refresh_token": "refresh_token_123",
"sealed_session": session_data,
"user": session_constants["TEST_USER"],
}
mock_user_management.authenticate_with_refresh_token.return_value = (
RefreshTokenAuthenticationResponse(**mock_response)
)
session = Session(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_data,
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = session.refresh()
assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
class TestAsyncSession(SessionFixtures):
@pytest.mark.asyncio
@with_jwks_mock
async def test_refresh_success(self, session_constants, mock_user_management):
session_data = AsyncSession.seal_data(
{
"refresh_token": "refresh_token_12345",
"user": session_constants["TEST_USER"],
},
session_constants["COOKIE_PASSWORD"],
)
mock_response = {
"access_token": session_constants["TEST_TOKEN"],
"refresh_token": "refresh_token_123",
"sealed_session": session_data,
"user": session_constants["TEST_USER"],
}
mock_user_management.authenticate_with_refresh_token = AsyncMock(
return_value=(RefreshTokenAuthenticationResponse(**mock_response))
)
session = AsyncSession(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_data,
cookie_password=session_constants["COOKIE_PASSWORD"],
)
with patch.object(session, "_is_valid_jwt", return_value=True) as _:
with patch(
"jwt.decode",
return_value={
"sid": session_constants["SESSION_ID"],
"org_id": session_constants["ORGANIZATION_ID"],
"role": "admin",
"permissions": ["read"],
"entitlements": ["feature_1"],
},
):
response = await session.refresh()
assert isinstance(response, RefreshWithSessionCookieSuccessResponse)
assert response.authenticated is True
assert response.user.id == session_constants["TEST_USER"]["id"]
# Verify the refresh token was used correctly
mock_user_management.authenticate_with_refresh_token.assert_called_once_with(
refresh_token="refresh_token_12345",
organization_id=None,
session={
"seal_session": True,
"cookie_password": session_constants["COOKIE_PASSWORD"],
},
)
@pytest.mark.asyncio
@with_jwks_mock
async def test_refresh_success_with_aud_claim(
self, session_constants, mock_user_management
):
session_data = AsyncSession.seal_data(
{
"refresh_token": "refresh_token_12345",
"user": session_constants["TEST_USER"],
},
session_constants["COOKIE_PASSWORD"],
)
access_token = jwt.encode(
{
**session_constants["TEST_TOKEN_CLAIMS"],
**{"aud": session_constants["CLIENT_ID"]},
},
session_constants["PRIVATE_KEY"],
algorithm="RS256",
)
mock_response = {
"access_token": access_token,
"refresh_token": "refresh_token_123",
"sealed_session": session_data,
"user": session_constants["TEST_USER"],
}
mock_user_management.authenticate_with_refresh_token = AsyncMock(
return_value=(RefreshTokenAuthenticationResponse(**mock_response))
)
session = AsyncSession(
user_management=mock_user_management,
client_id=session_constants["CLIENT_ID"],
session_data=session_data,
cookie_password=session_constants["COOKIE_PASSWORD"],
)
response = await session.refresh()
assert isinstance(response, RefreshWithSessionCookieSuccessResponse)