-
-
Notifications
You must be signed in to change notification settings - Fork 430
/
Copy pathtest_session.py
386 lines (286 loc) · 11 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
import base64
from collections import Counter
from datetime import timedelta
from typing import Iterable
import django
import pytest
from django.contrib.sessions.backends.cache import SessionStore
from django.test import override_settings
from django.utils import timezone
@pytest.fixture
def session(cache) -> Iterable[SessionStore]:
s = SessionStore()
yield s
s.delete()
def test_new_session(session):
assert session.modified is False
assert session.accessed is False
def test_get_empty(session):
assert session.get("cat") is None
def test_store(session):
session["cat"] = "dog"
assert session.modified is True
assert session.pop("cat") == "dog"
def test_pop(session):
session["some key"] = "exists"
# Need to reset these to pretend we haven't accessed it:
session.accessed = False
session.modified = False
assert session.pop("some key") == "exists"
assert session.accessed is True
assert session.modified is True
assert session.get("some key") is None
def test_pop_default(session):
assert session.pop("some key", "does not exist") == "does not exist"
assert session.accessed is True
assert session.modified is False
def test_pop_default_named_argument(session):
assert session.pop("some key", default="does not exist") == "does not exist"
assert session.accessed is True
assert session.modified is False
def test_pop_no_default_keyerror_raised(session):
with pytest.raises(KeyError):
session.pop("some key")
def test_setdefault(session):
assert session.setdefault("foo", "bar") == "bar"
assert session.setdefault("foo", "baz") == "bar"
assert session.accessed is True
assert session.modified is True
def test_update(session):
session.update({"update key": 1})
assert session.accessed is True
assert session.modified is True
assert session.get("update key") == 1
def test_has_key(session):
session["some key"] = 1
session.modified = False
session.accessed = False
assert "some key" in session
assert session.accessed is True
assert session.modified is False
def test_values(session):
assert list(session.values()) == []
assert session.accessed is True
session["some key"] = 1
session.modified = False
session.accessed = False
assert list(session.values()) == [1]
assert session.accessed is True
assert session.modified is False
def test_keys(session):
session["x"] = 1
session.modified = False
session.accessed = False
assert list(session.keys()) == ["x"]
assert session.accessed is True
assert session.modified is False
def test_items(session):
session["x"] = 1
session.modified = False
session.accessed = False
assert list(session.items()) == [("x", 1)]
assert session.accessed is True
assert session.modified is False
def test_clear(session):
session["x"] = 1
session.modified = False
session.accessed = False
assert list(session.items()) == [("x", 1)]
session.clear()
assert list(session.items()) == []
assert session.accessed is True
assert session.modified is True
def test_save(session):
session.save()
assert session.exists(session.session_key) is True
def test_delete(session):
session.save()
session.delete(session.session_key)
assert session.exists(session.session_key) is False
def test_flush(session):
session["foo"] = "bar"
session.save()
prev_key = session.session_key
session.flush()
assert session.exists(prev_key) is False
assert session.session_key != prev_key
assert session.session_key is None
assert session.modified is True
assert session.accessed is True
def test_cycle(session):
session["a"], session["b"] = "c", "d"
session.save()
prev_key = session.session_key
prev_data = list(session.items())
session.cycle_key()
assert session.exists(prev_key) is False
assert session.session_key != prev_key
assert list(session.items()) == prev_data
def test_cycle_with_no_session_cache(session):
session["a"], session["b"] = "c", "d"
session.save()
prev_data = session.items()
session = SessionStore(session.session_key)
assert hasattr(session, "_session_cache") is False
session.cycle_key()
assert Counter(session.items()) == Counter(prev_data)
def test_save_doesnt_clear_data(session):
session["a"] = "b"
session.save()
assert session["a"] == "b"
def test_invalid_key(session):
# Submitting an invalid session key (either by guessing, or if the db has
# removed the key) results in a new key being generated.
try:
session = SessionStore("1")
session.save()
assert session.session_key != "1"
assert session.get("cat") is None
session.delete()
finally:
# Some backends leave a stale cache entry for the invalid
# session key; make sure that entry is manually deleted
session.delete("1")
def test_session_key_empty_string_invalid(session):
"""Falsey values (Such as an empty string) are rejected."""
session._session_key = ""
assert session.session_key is None
def test_session_key_too_short_invalid(session):
"""Strings shorter than 8 characters are rejected."""
session._session_key = "1234567"
assert session.session_key is None
def test_session_key_valid_string_saved(session):
"""Strings of length 8 and up are accepted and stored."""
session._session_key = "12345678"
assert session.session_key == "12345678"
def test_session_key_is_read_only(session):
def set_session_key(s):
s.session_key = s._get_new_session_key()
with pytest.raises(AttributeError):
set_session_key(session)
# Custom session expiry
def test_default_expiry(session, settings):
# A normal session has a max age equal to settings
assert session.get_expiry_age() == settings.SESSION_COOKIE_AGE
# So does a custom session with an idle expiration time of 0 (but it'll
# expire at browser close)
session.set_expiry(0)
assert session.get_expiry_age() == settings.SESSION_COOKIE_AGE
def test_custom_expiry_seconds(session):
modification = timezone.now()
session.set_expiry(10)
date = session.get_expiry_date(modification=modification)
assert date == modification + timedelta(seconds=10)
age = session.get_expiry_age(modification=modification)
assert age == 10
def test_custom_expiry_timedelta(session):
modification = timezone.now()
# Mock timezone.now, because set_expiry calls it on this code path.
original_now = timezone.now
try:
timezone.now = lambda: modification
session.set_expiry(timedelta(seconds=10))
finally:
timezone.now = original_now
date = session.get_expiry_date(modification=modification)
assert date == modification + timedelta(seconds=10)
age = session.get_expiry_age(modification=modification)
assert age == 10
def test_custom_expiry_datetime(session):
modification = timezone.now()
session.set_expiry(modification + timedelta(seconds=10))
date = session.get_expiry_date(modification=modification)
assert date == modification + timedelta(seconds=10)
age = session.get_expiry_age(modification=modification)
assert age == 10
def test_custom_expiry_reset(session, settings):
session.set_expiry(None)
session.set_expiry(10)
session.set_expiry(None)
assert session.get_expiry_age() == settings.SESSION_COOKIE_AGE
def test_get_expire_at_browser_close(session):
# Tests get_expire_at_browser_close with different settings and different
# set_expiry calls
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False):
session.set_expiry(10)
assert session.get_expire_at_browser_close() is False
session.set_expiry(0)
assert session.get_expire_at_browser_close() is True
session.set_expiry(None)
assert session.get_expire_at_browser_close() is False
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True):
session.set_expiry(10)
assert session.get_expire_at_browser_close() is False
session.set_expiry(0)
assert session.get_expire_at_browser_close() is True
session.set_expiry(None)
assert session.get_expire_at_browser_close() is True
def test_decode(session):
# Ensure we can decode what we encode
data = {"a test key": "a test value"}
encoded = session.encode(data)
assert session.decode(encoded) == data
def test_decode_failure_logged_to_security(session, caplog):
bad_encode = base64.b64encode(b"flaskdj:alkdjf").decode("ascii")
# with self.assertLogs("django.security.SuspiciousSession", "WARNING") as cm:
assert session.decode(bad_encode) == {}
assert (
"django.security.SuspiciousSession",
30,
"Session data corrupted",
) in caplog.record_tuples
@pytest.mark.skipif(
django.VERSION >= (4, 2),
reason="PickleSerializer is removed as of https://code.djangoproject.com/ticket/29708",
)
def test_actual_expiry(session):
# this doesn't work with JSONSerializer (serializing timedelta)
with override_settings(
SESSION_SERIALIZER="django.contrib.sessions.serializers.PickleSerializer"
):
session = SessionStore() # reinitialize after overriding settings
# Regression test for #19200
old_session_key = None
new_session_key = None
try:
session["foo"] = "bar"
session.set_expiry(-timedelta(seconds=10))
session.save()
old_session_key = session.session_key
# With an expiry date in the past, the session expires instantly.
new_session = SessionStore(session.session_key)
new_session_key = new_session.session_key
assert "foo" not in new_session
finally:
session.delete(old_session_key)
session.delete(new_session_key)
def test_session_load_does_not_create_record(session):
"""
Loading an unknown session key does not create a session record.
Creating session records on load is a DOS vulnerability.
"""
session = SessionStore("someunknownkey")
session.load()
assert session.session_key is None
assert session.exists(session.session_key) is False
# provided unknown key was cycled, not reused
assert session.session_key != "someunknownkey"
def test_session_save_does_not_resurrect_session_logged_out_in_other_context(session):
"""
Sessions shouldn't be resurrected by a concurrent request.
"""
from django.contrib.sessions.backends.base import UpdateError
# Create new session.
s1 = SessionStore()
s1["test_data"] = "value1"
s1.save(must_create=True)
# Logout in another context.
s2 = SessionStore(s1.session_key)
s2.delete()
# Modify session in first context.
s1["test_data"] = "value2"
with pytest.raises(UpdateError):
# This should throw an exception as the session is deleted, not
# resurrect the session.
s1.save()
assert s1.load() == {}