2013-05-16 07:14:28 +08:00
|
|
|
import base64
|
2012-10-28 05:12:08 +08:00
|
|
|
import os
|
2010-10-11 20:55:17 +08:00
|
|
|
import shutil
|
2012-03-23 13:31:11 +08:00
|
|
|
import string
|
2010-10-11 20:55:17 +08:00
|
|
|
import tempfile
|
2013-07-01 20:22:27 +08:00
|
|
|
import unittest
|
2015-01-28 20:35:27 +08:00
|
|
|
from datetime import timedelta
|
2017-01-07 19:11:46 +08:00
|
|
|
from http import cookies
|
2010-10-11 20:55:17 +08:00
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
from django.conf import settings
|
2016-01-09 00:08:08 +08:00
|
|
|
from django.contrib.sessions.backends.base import UpdateError
|
2010-08-05 19:49:58 +08:00
|
|
|
from django.contrib.sessions.backends.cache import SessionStore as CacheSession
|
2017-06-02 01:23:48 +08:00
|
|
|
from django.contrib.sessions.backends.cached_db import (
|
|
|
|
SessionStore as CacheDBSession,
|
|
|
|
)
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.sessions.backends.db import SessionStore as DatabaseSession
|
2010-08-05 19:49:58 +08:00
|
|
|
from django.contrib.sessions.backends.file import SessionStore as FileSession
|
2017-06-02 01:23:48 +08:00
|
|
|
from django.contrib.sessions.backends.signed_cookies import (
|
|
|
|
SessionStore as CookieSession,
|
|
|
|
)
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.sessions.exceptions import InvalidSessionKey
|
2010-11-26 21:30:50 +08:00
|
|
|
from django.contrib.sessions.middleware import SessionMiddleware
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.sessions.models import Session
|
2015-03-12 01:46:39 +08:00
|
|
|
from django.contrib.sessions.serializers import (
|
|
|
|
JSONSerializer, PickleSerializer,
|
|
|
|
)
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core import management
|
2013-10-19 06:49:24 +08:00
|
|
|
from django.core.cache import caches
|
2013-08-30 12:03:23 +08:00
|
|
|
from django.core.cache.backends.base import InvalidCacheBackendError
|
2016-10-25 19:23:14 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
|
2010-11-26 21:30:50 +08:00
|
|
|
from django.http import HttpResponse
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.test import (
|
|
|
|
RequestFactory, TestCase, ignore_warnings, override_settings,
|
|
|
|
)
|
2017-01-07 19:11:46 +08:00
|
|
|
from django.utils import timezone
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2016-02-05 00:47:20 +08:00
|
|
|
from .models import SessionStore as CustomDatabaseSession
|
2014-05-17 00:18:34 +08:00
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class SessionTestsMixin:
|
2010-08-05 19:49:58 +08:00
|
|
|
# This does not inherit from TestCase to avoid any tests being run with this
|
|
|
|
# class, which wouldn't work, and to allow different TestCase subclasses to
|
|
|
|
# be used.
|
|
|
|
|
2012-03-23 13:31:11 +08:00
|
|
|
backend = None # subclasses must specify
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
self.session = self.backend()
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
# NB: be careful to delete any sessions created; stale sessions fill up
|
|
|
|
# the /tmp (with some backends) and eventually overwhelm it after lots
|
|
|
|
# of runs (think buildbots)
|
|
|
|
self.session.delete()
|
|
|
|
|
|
|
|
def test_new_session(self):
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.modified, False)
|
|
|
|
self.assertIs(self.session.accessed, False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_get_empty(self):
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNone(self.session.get('cat'))
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_store(self):
|
|
|
|
self.session['cat'] = "dog"
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertEqual(self.session.pop('cat'), 'dog')
|
|
|
|
|
|
|
|
def test_pop(self):
|
|
|
|
self.session['some key'] = 'exists'
|
|
|
|
# Need to reset these to pretend we haven't accessed it:
|
|
|
|
self.accessed = False
|
|
|
|
self.modified = False
|
|
|
|
|
|
|
|
self.assertEqual(self.session.pop('some key'), 'exists')
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNone(self.session.get('some key'))
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_pop_default(self):
|
|
|
|
self.assertEqual(self.session.pop('some key', 'does not exist'),
|
|
|
|
'does not exist')
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2016-04-20 23:04:58 +08:00
|
|
|
def test_pop_default_named_argument(self):
|
|
|
|
self.assertEqual(self.session.pop('some key', default='does not exist'), 'does not exist')
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2016-04-20 23:04:58 +08:00
|
|
|
|
2016-04-20 16:36:59 +08:00
|
|
|
def test_pop_no_default_keyerror_raised(self):
|
|
|
|
with self.assertRaises(KeyError):
|
|
|
|
self.session.pop('some key')
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
def test_setdefault(self):
|
|
|
|
self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar')
|
|
|
|
self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar')
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_update(self):
|
|
|
|
self.session.update({'update key': 1})
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertEqual(self.session.get('update key', None), 1)
|
|
|
|
|
|
|
|
def test_has_key(self):
|
|
|
|
self.session['some key'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2012-10-28 01:18:03 +08:00
|
|
|
self.assertIn('some key', self.session)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_values(self):
|
2012-07-21 03:14:27 +08:00
|
|
|
self.assertEqual(list(self.session.values()), [])
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session['some key'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2017-01-20 02:16:22 +08:00
|
|
|
self.assertEqual(list(self.session.values()), [1])
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2017-01-20 02:16:22 +08:00
|
|
|
def test_keys(self):
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2017-01-20 02:16:22 +08:00
|
|
|
self.assertEqual(list(self.session.keys()), ['x'])
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2017-01-20 02:16:22 +08:00
|
|
|
def test_items(self):
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2017-01-20 02:16:22 +08:00
|
|
|
self.assertEqual(list(self.session.items()), [('x', 1)])
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_clear(self):
|
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2012-07-21 03:14:27 +08:00
|
|
|
self.assertEqual(list(self.session.items()), [('x', 1)])
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session.clear()
|
2012-07-21 03:14:27 +08:00
|
|
|
self.assertEqual(list(self.session.items()), [])
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_save(self):
|
|
|
|
self.session.save()
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.exists(self.session.session_key), True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_delete(self):
|
2011-11-28 01:52:24 +08:00
|
|
|
self.session.save()
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session.delete(self.session.session_key)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.exists(self.session.session_key), False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_flush(self):
|
|
|
|
self.session['foo'] = 'bar'
|
|
|
|
self.session.save()
|
|
|
|
prev_key = self.session.session_key
|
|
|
|
self.session.flush()
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.exists(prev_key), False)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertNotEqual(self.session.session_key, prev_key)
|
2015-05-11 21:58:43 +08:00
|
|
|
self.assertIsNone(self.session.session_key)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.modified, True)
|
|
|
|
self.assertIs(self.session.accessed, True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_cycle(self):
|
|
|
|
self.session['a'], self.session['b'] = 'c', 'd'
|
|
|
|
self.session.save()
|
|
|
|
prev_key = self.session.session_key
|
2012-07-21 03:14:27 +08:00
|
|
|
prev_data = list(self.session.items())
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session.cycle_key()
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.exists(prev_key), False)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertNotEqual(self.session.session_key, prev_key)
|
2012-07-21 03:14:27 +08:00
|
|
|
self.assertEqual(list(self.session.items()), prev_data)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2016-08-09 01:01:25 +08:00
|
|
|
def test_cycle_with_no_session_cache(self):
|
2017-04-12 08:35:17 +08:00
|
|
|
self.session['a'], self.session['b'] = 'c', 'd'
|
|
|
|
self.session.save()
|
2017-04-18 23:56:59 +08:00
|
|
|
prev_data = self.session.items()
|
2017-04-12 08:35:17 +08:00
|
|
|
self.session = self.backend(self.session.session_key)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(hasattr(self.session, '_session_cache'), False)
|
2016-08-09 01:01:25 +08:00
|
|
|
self.session.cycle_key()
|
2017-04-18 23:56:59 +08:00
|
|
|
self.assertCountEqual(self.session.items(), prev_data)
|
2016-08-09 01:01:25 +08:00
|
|
|
|
2015-06-11 05:45:20 +08:00
|
|
|
def test_save_doesnt_clear_data(self):
|
|
|
|
self.session['a'] = 'b'
|
|
|
|
self.session.save()
|
|
|
|
self.assertEqual(self.session['a'], 'b')
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
def test_invalid_key(self):
|
|
|
|
# Submitting an invalid session key (either by guessing, or if the db has
|
|
|
|
# removed the key) results in a new key being generated.
|
2011-01-17 22:03:19 +08:00
|
|
|
try:
|
|
|
|
session = self.backend('1')
|
2016-06-28 23:21:26 +08:00
|
|
|
session.save()
|
2011-01-17 22:03:19 +08:00
|
|
|
self.assertNotEqual(session.session_key, '1')
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNone(session.get('cat'))
|
2011-01-17 22:03:19 +08:00
|
|
|
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')
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2015-06-05 20:48:41 +08:00
|
|
|
def test_session_key_empty_string_invalid(self):
|
|
|
|
"""Falsey values (Such as an empty string) are rejected."""
|
|
|
|
self.session._session_key = ''
|
|
|
|
self.assertIsNone(self.session.session_key)
|
|
|
|
|
|
|
|
def test_session_key_too_short_invalid(self):
|
|
|
|
"""Strings shorter than 8 characters are rejected."""
|
|
|
|
self.session._session_key = '1234567'
|
|
|
|
self.assertIsNone(self.session.session_key)
|
|
|
|
|
|
|
|
def test_session_key_valid_string_saved(self):
|
|
|
|
"""Strings of length 8 and up are accepted and stored."""
|
|
|
|
self.session._session_key = '12345678'
|
|
|
|
self.assertEqual(self.session.session_key, '12345678')
|
|
|
|
|
2011-11-28 01:52:24 +08:00
|
|
|
def test_session_key_is_read_only(self):
|
|
|
|
def set_session_key(session):
|
|
|
|
session.session_key = session._get_new_session_key()
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(AttributeError):
|
|
|
|
set_session_key(self.session)
|
2011-11-28 01:52:24 +08:00
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
# Custom session expiry
|
|
|
|
def test_default_expiry(self):
|
|
|
|
# A normal session has a max age equal to settings
|
|
|
|
self.assertEqual(self.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)
|
|
|
|
self.session.set_expiry(0)
|
|
|
|
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
|
|
|
|
|
|
|
|
def test_custom_expiry_seconds(self):
|
2012-10-28 03:32:50 +08:00
|
|
|
modification = timezone.now()
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session.set_expiry(10)
|
|
|
|
|
2012-10-28 03:32:50 +08:00
|
|
|
date = self.session.get_expiry_date(modification=modification)
|
|
|
|
self.assertEqual(date, modification + timedelta(seconds=10))
|
|
|
|
|
|
|
|
age = self.session.get_expiry_age(modification=modification)
|
|
|
|
self.assertEqual(age, 10)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_custom_expiry_timedelta(self):
|
2012-10-28 03:32:50 +08:00
|
|
|
modification = timezone.now()
|
|
|
|
|
|
|
|
# Mock timezone.now, because set_expiry calls it on this code path.
|
|
|
|
original_now = timezone.now
|
|
|
|
try:
|
|
|
|
timezone.now = lambda: modification
|
|
|
|
self.session.set_expiry(timedelta(seconds=10))
|
|
|
|
finally:
|
|
|
|
timezone.now = original_now
|
|
|
|
|
|
|
|
date = self.session.get_expiry_date(modification=modification)
|
|
|
|
self.assertEqual(date, modification + timedelta(seconds=10))
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2012-10-28 03:32:50 +08:00
|
|
|
age = self.session.get_expiry_age(modification=modification)
|
|
|
|
self.assertEqual(age, 10)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-02-01 02:37:28 +08:00
|
|
|
def test_custom_expiry_datetime(self):
|
2012-10-28 03:32:50 +08:00
|
|
|
modification = timezone.now()
|
|
|
|
|
|
|
|
self.session.set_expiry(modification + timedelta(seconds=10))
|
|
|
|
|
|
|
|
date = self.session.get_expiry_date(modification=modification)
|
|
|
|
self.assertEqual(date, modification + timedelta(seconds=10))
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2012-10-28 03:32:50 +08:00
|
|
|
age = self.session.get_expiry_age(modification=modification)
|
|
|
|
self.assertEqual(age, 10)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_custom_expiry_reset(self):
|
|
|
|
self.session.set_expiry(None)
|
|
|
|
self.session.set_expiry(10)
|
|
|
|
self.session.set_expiry(None)
|
|
|
|
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
|
|
|
|
|
|
|
|
def test_get_expire_at_browser_close(self):
|
|
|
|
# Tests get_expire_at_browser_close with different settings and different
|
|
|
|
# set_expiry calls
|
2011-06-27 01:00:24 +08:00
|
|
|
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False):
|
|
|
|
self.session.set_expiry(10)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(0)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(None)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True):
|
|
|
|
self.session.set_expiry(10)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), False)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(0)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(None)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), True)
|
2010-08-05 19:49:58 +08:00
|
|
|
|
Fixed #14445 - Use HMAC and constant-time comparison functions where needed.
All adhoc MAC applications have been updated to use HMAC, using SHA1 to
generate unique keys for each application based on the SECRET_KEY, which is
common practice for this situation. In all cases, backwards compatibility
with existing hashes has been maintained, aiming to phase this out as per
the normal deprecation process. In this way, under most normal
circumstances the old hashes will have expired (e.g. by session expiration
etc.) before they become invalid.
In the case of the messages framework and the cookie backend, which was
already using HMAC, there is the possibility of a backwards incompatibility
if the SECRET_KEY is shorter than the default 50 bytes, but the low
likelihood and low impact meant compatibility code was not worth it.
All known instances where tokens/hashes were compared using simple string
equality, which could potentially open timing based attacks, have also been
fixed using a constant-time comparison function.
There are no known practical attacks against the existing implementations,
so these security improvements will not be backported.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@14218 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2010-10-15 04:54:30 +08:00
|
|
|
def test_decode(self):
|
|
|
|
# Ensure we can decode what we encode
|
|
|
|
data = {'a test key': 'a test value'}
|
|
|
|
encoded = self.session.encode(data)
|
|
|
|
self.assertEqual(self.session.decode(encoded), data)
|
|
|
|
|
2013-05-16 07:14:28 +08:00
|
|
|
def test_decode_failure_logged_to_security(self):
|
2018-10-03 12:04:12 +08:00
|
|
|
bad_encode = base64.b64encode(b'flaskdj:alkdjf').decode('ascii')
|
2018-04-28 21:20:27 +08:00
|
|
|
with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm:
|
2013-05-16 07:14:28 +08:00
|
|
|
self.assertEqual({}, self.session.decode(bad_encode))
|
2018-04-28 21:20:27 +08:00
|
|
|
# The failed decode is logged.
|
|
|
|
self.assertIn('corrupted', cm.output[0])
|
2013-05-16 07:14:28 +08:00
|
|
|
|
2012-10-28 01:18:03 +08:00
|
|
|
def test_actual_expiry(self):
|
2013-08-22 08:12:19 +08:00
|
|
|
# this doesn't work with JSONSerializer (serializing timedelta)
|
|
|
|
with override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'):
|
|
|
|
self.session = self.backend() # reinitialize after overriding settings
|
|
|
|
|
|
|
|
# Regression test for #19200
|
|
|
|
old_session_key = None
|
|
|
|
new_session_key = None
|
|
|
|
try:
|
|
|
|
self.session['foo'] = 'bar'
|
|
|
|
self.session.set_expiry(-timedelta(seconds=10))
|
|
|
|
self.session.save()
|
|
|
|
old_session_key = self.session.session_key
|
|
|
|
# With an expiry date in the past, the session expires instantly.
|
|
|
|
new_session = self.backend(self.session.session_key)
|
|
|
|
new_session_key = new_session.session_key
|
|
|
|
self.assertNotIn('foo', new_session)
|
|
|
|
finally:
|
|
|
|
self.session.delete(old_session_key)
|
|
|
|
self.session.delete(new_session_key)
|
2012-10-28 01:18:03 +08:00
|
|
|
|
2015-06-11 05:45:20 +08:00
|
|
|
def test_session_load_does_not_create_record(self):
|
|
|
|
"""
|
|
|
|
Loading an unknown session key does not create a session record.
|
|
|
|
|
|
|
|
Creating session records on load is a DOS vulnerability.
|
|
|
|
"""
|
|
|
|
session = self.backend('someunknownkey')
|
|
|
|
session.load()
|
|
|
|
|
2017-05-03 22:09:28 +08:00
|
|
|
self.assertIsNone(session.session_key)
|
|
|
|
self.assertIs(session.exists(session.session_key), False)
|
2015-06-11 05:45:20 +08:00
|
|
|
# provided unknown key was cycled, not reused
|
|
|
|
self.assertNotEqual(session.session_key, 'someunknownkey')
|
|
|
|
|
2016-01-09 00:08:08 +08:00
|
|
|
def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self):
|
|
|
|
"""
|
|
|
|
Sessions shouldn't be resurrected by a concurrent request.
|
|
|
|
"""
|
|
|
|
# Create new session.
|
|
|
|
s1 = self.backend()
|
|
|
|
s1['test_data'] = 'value1'
|
|
|
|
s1.save(must_create=True)
|
|
|
|
|
|
|
|
# Logout in another context.
|
|
|
|
s2 = self.backend(s1.session_key)
|
|
|
|
s2.delete()
|
|
|
|
|
|
|
|
# Modify session in first context.
|
|
|
|
s1['test_data'] = 'value2'
|
|
|
|
with self.assertRaises(UpdateError):
|
|
|
|
# This should throw an exception as the session is deleted, not
|
|
|
|
# resurrect the session.
|
|
|
|
s1.save()
|
|
|
|
|
|
|
|
self.assertEqual(s1.load(), {})
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
class DatabaseSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
backend = DatabaseSession
|
2014-05-17 00:18:34 +08:00
|
|
|
session_engine = 'django.contrib.sessions.backends.db'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def model(self):
|
|
|
|
return self.backend.get_model_class()
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2014-07-25 04:24:01 +08:00
|
|
|
def test_session_str(self):
|
|
|
|
"Session repr should be the session key."
|
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
session_key = self.session.session_key
|
2014-05-17 00:18:34 +08:00
|
|
|
s = self.model.objects.get(session_key=session_key)
|
2014-07-25 04:24:01 +08:00
|
|
|
|
2017-01-24 19:22:42 +08:00
|
|
|
self.assertEqual(str(s), session_key)
|
2014-07-25 04:24:01 +08:00
|
|
|
|
2010-11-15 06:23:46 +08:00
|
|
|
def test_session_get_decoded(self):
|
|
|
|
"""
|
|
|
|
Test we can use Session.get_decoded to retrieve data stored
|
|
|
|
in normal way
|
|
|
|
"""
|
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.save()
|
|
|
|
|
2014-05-17 00:18:34 +08:00
|
|
|
s = self.model.objects.get(session_key=self.session.session_key)
|
2010-11-15 06:23:46 +08:00
|
|
|
|
|
|
|
self.assertEqual(s.get_decoded(), {'x': 1})
|
|
|
|
|
|
|
|
def test_sessionmanager_save(self):
|
|
|
|
"""
|
|
|
|
Test SessionManager.save method
|
|
|
|
"""
|
|
|
|
# Create a session
|
|
|
|
self.session['y'] = 1
|
|
|
|
self.session.save()
|
|
|
|
|
2014-05-17 00:18:34 +08:00
|
|
|
s = self.model.objects.get(session_key=self.session.session_key)
|
2010-11-15 06:23:46 +08:00
|
|
|
# Change it
|
2014-05-17 00:18:34 +08:00
|
|
|
self.model.objects.save(s.session_key, {'y': 2}, s.expire_date)
|
2010-11-15 06:23:46 +08:00
|
|
|
# Clear cache, so that it will be retrieved from DB
|
|
|
|
del self.session._session_cache
|
|
|
|
self.assertEqual(self.session['y'], 2)
|
|
|
|
|
2012-10-28 05:12:08 +08:00
|
|
|
def test_clearsessions_command(self):
|
|
|
|
"""
|
|
|
|
Test clearsessions command for clearing expired sessions.
|
|
|
|
"""
|
2014-05-17 00:18:34 +08:00
|
|
|
self.assertEqual(0, self.model.objects.count())
|
2012-10-28 05:12:08 +08:00
|
|
|
|
|
|
|
# One object in the future
|
|
|
|
self.session['foo'] = 'bar'
|
|
|
|
self.session.set_expiry(3600)
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
# One object in the past
|
|
|
|
other_session = self.backend()
|
|
|
|
other_session['foo'] = 'bar'
|
|
|
|
other_session.set_expiry(-3600)
|
|
|
|
other_session.save()
|
|
|
|
|
|
|
|
# Two sessions are in the database before clearsessions...
|
2014-05-17 00:18:34 +08:00
|
|
|
self.assertEqual(2, self.model.objects.count())
|
|
|
|
with override_settings(SESSION_ENGINE=self.session_engine):
|
|
|
|
management.call_command('clearsessions')
|
2012-10-28 05:12:08 +08:00
|
|
|
# ... and one is deleted.
|
2014-05-17 00:18:34 +08:00
|
|
|
self.assertEqual(1, self.model.objects.count())
|
2012-10-28 05:12:08 +08:00
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(USE_TZ=True)
|
|
|
|
class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests):
|
|
|
|
pass
|
2011-11-20 18:33:44 +08:00
|
|
|
|
|
|
|
|
2014-05-17 00:18:34 +08:00
|
|
|
class CustomDatabaseSessionTests(DatabaseSessionTests):
|
|
|
|
backend = CustomDatabaseSession
|
2016-02-05 00:47:20 +08:00
|
|
|
session_engine = 'sessions_tests.models'
|
2014-05-17 00:18:34 +08:00
|
|
|
|
|
|
|
def test_extra_session_field(self):
|
|
|
|
# Set the account ID to be picked up by a custom session storage
|
|
|
|
# and saved to a custom session model database column.
|
|
|
|
self.session['_auth_user_id'] = 42
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
# Make sure that the customized create_model_instance() was called.
|
|
|
|
s = self.model.objects.get(session_key=self.session.session_key)
|
|
|
|
self.assertEqual(s.account_id, 42)
|
|
|
|
|
|
|
|
# Make the session "anonymous".
|
|
|
|
self.session.pop('_auth_user_id')
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
# Make sure that save() on an existing session did the right job.
|
|
|
|
s = self.model.objects.get(session_key=self.session.session_key)
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNone(s.account_id)
|
2014-05-17 00:18:34 +08:00
|
|
|
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
class CacheDBSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
backend = CacheDBSession
|
|
|
|
|
2011-11-28 02:36:03 +08:00
|
|
|
def test_exists_searches_cache_first(self):
|
|
|
|
self.session.save()
|
|
|
|
with self.assertNumQueries(0):
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(self.session.exists(self.session.session_key), True)
|
2011-11-28 02:36:03 +08:00
|
|
|
|
2014-12-22 04:19:05 +08:00
|
|
|
# Some backends might issue a warning
|
|
|
|
@ignore_warnings(module="django.core.cache.backends.base")
|
2012-03-23 13:31:11 +08:00
|
|
|
def test_load_overlong_key(self):
|
2014-12-22 04:19:05 +08:00
|
|
|
self.session._session_key = (string.ascii_letters + string.digits) * 20
|
|
|
|
self.assertEqual(self.session.load(), {})
|
2012-03-23 13:31:11 +08:00
|
|
|
|
2013-08-30 12:03:23 +08:00
|
|
|
@override_settings(SESSION_CACHE_ALIAS='sessions')
|
|
|
|
def test_non_default_cache(self):
|
2013-11-03 05:02:56 +08:00
|
|
|
# 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS.
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(InvalidCacheBackendError):
|
|
|
|
self.backend()
|
2013-08-30 12:03:23 +08:00
|
|
|
|
2011-11-20 18:33:44 +08:00
|
|
|
|
2012-03-30 17:08:29 +08:00
|
|
|
@override_settings(USE_TZ=True)
|
|
|
|
class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests):
|
|
|
|
pass
|
2011-11-20 18:33:44 +08:00
|
|
|
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
# Don't need DB flushing for these tests, so can use unittest.TestCase as base class
|
|
|
|
class FileSessionTests(SessionTestsMixin, unittest.TestCase):
|
|
|
|
|
|
|
|
backend = FileSession
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
# Do file session tests in an isolated directory, and kill it after we're done.
|
|
|
|
self.original_session_file_path = settings.SESSION_FILE_PATH
|
|
|
|
self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp()
|
2012-10-28 05:12:08 +08:00
|
|
|
# Reset the file session backend's internal caches
|
|
|
|
if hasattr(self.backend, '_storage_path'):
|
|
|
|
del self.backend._storage_path
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUp()
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDown()
|
2010-08-05 19:49:58 +08:00
|
|
|
settings.SESSION_FILE_PATH = self.original_session_file_path
|
|
|
|
shutil.rmtree(self.temp_session_store)
|
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
@override_settings(
|
2018-03-16 17:54:34 +08:00
|
|
|
SESSION_FILE_PATH='/if/this/directory/exists/you/have/a/weird/computer',
|
|
|
|
)
|
2010-08-05 19:49:58 +08:00
|
|
|
def test_configuration_check(self):
|
2012-10-28 05:12:08 +08:00
|
|
|
del self.backend._storage_path
|
2010-08-05 19:49:58 +08:00
|
|
|
# Make sure the file backend checks for a good storage dir
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(ImproperlyConfigured):
|
|
|
|
self.backend()
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2013-05-19 21:25:49 +08:00
|
|
|
def test_invalid_key_backslash(self):
|
|
|
|
# Ensure we don't allow directory-traversal.
|
|
|
|
# This is tested directly on _key_to_file, as load() will swallow
|
2019-01-28 23:01:35 +08:00
|
|
|
# a SuspiciousOperation in the same way as an OSError - by creating
|
2013-05-19 21:25:49 +08:00
|
|
|
# a new session, making it unclear whether the slashes were detected.
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(InvalidSessionKey):
|
|
|
|
self.backend()._key_to_file("a\\b\\c")
|
2011-02-09 10:13:24 +08:00
|
|
|
|
|
|
|
def test_invalid_key_forwardslash(self):
|
|
|
|
# Ensure we don't allow directory-traversal
|
2016-01-17 19:26:39 +08:00
|
|
|
with self.assertRaises(InvalidSessionKey):
|
|
|
|
self.backend()._key_to_file("a/b/c")
|
2011-02-09 10:13:24 +08:00
|
|
|
|
2015-03-23 19:52:17 +08:00
|
|
|
@override_settings(
|
|
|
|
SESSION_ENGINE="django.contrib.sessions.backends.file",
|
|
|
|
SESSION_COOKIE_AGE=0,
|
|
|
|
)
|
2012-10-28 05:12:08 +08:00
|
|
|
def test_clearsessions_command(self):
|
|
|
|
"""
|
|
|
|
Test clearsessions command for clearing expired sessions.
|
|
|
|
"""
|
|
|
|
storage_path = self.backend._get_storage_path()
|
|
|
|
file_prefix = settings.SESSION_COOKIE_NAME
|
|
|
|
|
|
|
|
def count_sessions():
|
2016-04-08 10:04:45 +08:00
|
|
|
return len([
|
|
|
|
session_file for session_file in os.listdir(storage_path)
|
|
|
|
if session_file.startswith(file_prefix)
|
|
|
|
])
|
2012-10-28 05:12:08 +08:00
|
|
|
|
|
|
|
self.assertEqual(0, count_sessions())
|
|
|
|
|
|
|
|
# One object in the future
|
|
|
|
self.session['foo'] = 'bar'
|
|
|
|
self.session.set_expiry(3600)
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
# One object in the past
|
|
|
|
other_session = self.backend()
|
|
|
|
other_session['foo'] = 'bar'
|
|
|
|
other_session.set_expiry(-3600)
|
|
|
|
other_session.save()
|
|
|
|
|
2015-03-23 19:52:17 +08:00
|
|
|
# One object in the present without an expiry (should be deleted since
|
|
|
|
# its modification time + SESSION_COOKIE_AGE will be in the past when
|
|
|
|
# clearsessions runs).
|
|
|
|
other_session2 = self.backend()
|
|
|
|
other_session2['foo'] = 'bar'
|
|
|
|
other_session2.save()
|
|
|
|
|
|
|
|
# Three sessions are in the filesystem before clearsessions...
|
|
|
|
self.assertEqual(3, count_sessions())
|
2012-10-28 05:12:08 +08:00
|
|
|
management.call_command('clearsessions')
|
2015-03-23 19:52:17 +08:00
|
|
|
# ... and two are deleted.
|
2012-10-28 05:12:08 +08:00
|
|
|
self.assertEqual(1, count_sessions())
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
|
|
|
|
|
|
|
|
backend = CacheSession
|
2010-11-26 21:30:50 +08:00
|
|
|
|
2014-12-22 04:19:05 +08:00
|
|
|
# Some backends might issue a warning
|
|
|
|
@ignore_warnings(module="django.core.cache.backends.base")
|
2012-03-23 13:31:11 +08:00
|
|
|
def test_load_overlong_key(self):
|
2014-12-22 04:19:05 +08:00
|
|
|
self.session._session_key = (string.ascii_letters + string.digits) * 20
|
|
|
|
self.assertEqual(self.session.load(), {})
|
2012-03-23 13:31:11 +08:00
|
|
|
|
2012-10-31 04:59:23 +08:00
|
|
|
def test_default_cache(self):
|
|
|
|
self.session.save()
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNotNone(caches['default'].get(self.session.cache_key))
|
2012-10-31 04:59:23 +08:00
|
|
|
|
|
|
|
@override_settings(CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
|
|
|
|
},
|
|
|
|
'sessions': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
2013-10-19 06:49:24 +08:00
|
|
|
'LOCATION': 'session',
|
2012-10-31 04:59:23 +08:00
|
|
|
},
|
|
|
|
}, SESSION_CACHE_ALIAS='sessions')
|
|
|
|
def test_non_default_cache(self):
|
2014-04-27 01:18:45 +08:00
|
|
|
# Re-initialize the session backend to make use of overridden settings.
|
2013-02-23 23:33:28 +08:00
|
|
|
self.session = self.backend()
|
|
|
|
|
2012-10-31 04:59:23 +08:00
|
|
|
self.session.save()
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNone(caches['default'].get(self.session.cache_key))
|
|
|
|
self.assertIsNotNone(caches['sessions'].get(self.session.cache_key))
|
2012-10-31 04:59:23 +08:00
|
|
|
|
2016-04-04 06:09:10 +08:00
|
|
|
def test_create_and_save(self):
|
|
|
|
self.session = self.backend()
|
|
|
|
self.session.create()
|
|
|
|
self.session.save()
|
|
|
|
self.assertIsNotNone(caches['default'].get(self.session.cache_key))
|
|
|
|
|
2010-11-26 21:30:50 +08:00
|
|
|
|
2015-01-28 22:05:47 +08:00
|
|
|
class SessionMiddlewareTests(TestCase):
|
2018-11-27 03:01:27 +08:00
|
|
|
request_factory = RequestFactory()
|
2010-11-26 21:30:50 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
@override_settings(SESSION_COOKIE_SECURE=True)
|
2010-11-26 21:30:50 +08:00
|
|
|
def test_secure_session_cookie(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2010-11-26 21:30:50 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Simulate a request the modifies the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True)
|
2010-11-26 21:30:50 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
@override_settings(SESSION_COOKIE_HTTPONLY=True)
|
2010-11-26 21:30:50 +08:00
|
|
|
def test_httponly_session_cookie(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2010-11-26 21:30:50 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Simulate a request the modifies the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], True)
|
2016-04-08 10:04:45 +08:00
|
|
|
self.assertIn(
|
2017-01-07 19:11:46 +08:00
|
|
|
cookies.Morsel._reserved['httponly'],
|
2016-04-08 10:04:45 +08:00
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
2011-11-22 06:03:03 +08:00
|
|
|
|
2018-04-14 08:58:31 +08:00
|
|
|
@override_settings(SESSION_COOKIE_SAMESITE='Strict')
|
|
|
|
def test_samesite_session_cookie(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2018-04-14 08:58:31 +08:00
|
|
|
response = HttpResponse()
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict')
|
|
|
|
|
2011-11-22 06:03:03 +08:00
|
|
|
@override_settings(SESSION_COOKIE_HTTPONLY=False)
|
|
|
|
def test_no_httponly_session_cookie(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2011-11-22 06:03:03 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Simulate a request the modifies the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
2017-05-04 08:21:39 +08:00
|
|
|
self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '')
|
|
|
|
self.assertNotIn(
|
|
|
|
cookies.Morsel._reserved['httponly'],
|
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
2011-06-27 01:00:24 +08:00
|
|
|
|
2012-07-05 23:09:48 +08:00
|
|
|
def test_session_save_on_500(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2012-07-05 23:09:48 +08:00
|
|
|
response = HttpResponse('Horrible error')
|
|
|
|
response.status_code = 500
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Simulate a request the modifies the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
|
2016-10-27 15:53:39 +08:00
|
|
|
# The value wasn't saved above.
|
2012-07-05 23:09:48 +08:00
|
|
|
self.assertNotIn('hello', request.session.load())
|
|
|
|
|
2016-01-09 00:08:08 +08:00
|
|
|
def test_session_update_error_redirect(self):
|
|
|
|
path = '/foo/'
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get(path)
|
2016-01-09 00:08:08 +08:00
|
|
|
response = HttpResponse()
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
request.session = DatabaseSession()
|
|
|
|
request.session.save(must_create=True)
|
|
|
|
request.session.delete()
|
|
|
|
|
2016-10-25 19:23:14 +08:00
|
|
|
msg = (
|
|
|
|
"The request's session was deleted before the request completed. "
|
|
|
|
"The user may have logged out in a concurrent request, for example."
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(SuspiciousOperation, msg):
|
|
|
|
# Handle the response through the middleware. It will try to save
|
|
|
|
# the deleted session which will cause an UpdateError that's caught
|
|
|
|
# and raised as a SuspiciousOperation.
|
|
|
|
middleware.process_response(request, response)
|
2016-01-09 00:08:08 +08:00
|
|
|
|
2013-08-19 13:36:36 +08:00
|
|
|
def test_session_delete_on_end(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2013-08-19 13:36:36 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Before deleting, there has to be an existing cookie
|
|
|
|
request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'
|
|
|
|
|
|
|
|
# Simulate a request that ends the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session.flush()
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
|
2016-10-27 15:53:39 +08:00
|
|
|
# The cookie was deleted, not recreated.
|
2013-08-19 13:36:36 +08:00
|
|
|
# A deleted cookie header looks like:
|
2017-12-28 05:49:46 +08:00
|
|
|
# Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
|
2014-09-04 20:15:09 +08:00
|
|
|
self.assertEqual(
|
2017-12-28 05:49:46 +08:00
|
|
|
'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
|
2015-03-31 00:29:56 +08:00
|
|
|
'Max-Age=0; Path=/'.format(
|
|
|
|
settings.SESSION_COOKIE_NAME,
|
|
|
|
),
|
2014-09-04 20:15:09 +08:00
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
2013-08-19 13:36:36 +08:00
|
|
|
|
2016-06-21 23:03:25 +08:00
|
|
|
@override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/')
|
|
|
|
def test_session_delete_on_end_with_custom_domain_and_path(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2015-05-14 14:22:42 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Before deleting, there has to be an existing cookie
|
|
|
|
request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'
|
|
|
|
|
|
|
|
# Simulate a request that ends the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session.flush()
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
|
2016-10-27 15:53:39 +08:00
|
|
|
# The cookie was deleted, not recreated.
|
2016-06-21 23:03:25 +08:00
|
|
|
# A deleted cookie header with a custom domain and path looks like:
|
2015-05-14 14:22:42 +08:00
|
|
|
# Set-Cookie: sessionid=; Domain=.example.local;
|
2017-12-28 05:49:46 +08:00
|
|
|
# expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
|
2016-06-21 23:03:25 +08:00
|
|
|
# Path=/example/
|
2015-05-14 14:22:42 +08:00
|
|
|
self.assertEqual(
|
2017-02-18 08:45:34 +08:00
|
|
|
'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
|
2017-12-28 05:49:46 +08:00
|
|
|
'01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format(
|
2015-05-14 14:22:42 +08:00
|
|
|
settings.SESSION_COOKIE_NAME,
|
|
|
|
),
|
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
|
|
|
|
2015-08-06 04:51:42 +08:00
|
|
|
def test_flush_empty_without_session_cookie_doesnt_set_cookie(self):
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2015-08-06 04:51:42 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Simulate a request that ends the session
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session.flush()
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
|
|
|
|
# A cookie should not be set.
|
|
|
|
self.assertEqual(response.cookies, {})
|
|
|
|
# The session is accessed so "Vary: Cookie" should be set.
|
|
|
|
self.assertEqual(response['Vary'], 'Cookie')
|
|
|
|
|
2015-08-19 05:57:01 +08:00
|
|
|
def test_empty_session_saved(self):
|
2015-10-20 17:30:43 +08:00
|
|
|
"""
|
2015-08-19 05:57:01 +08:00
|
|
|
If a session is emptied of data but still has a key, it should still
|
|
|
|
be updated.
|
|
|
|
"""
|
2018-11-27 03:01:27 +08:00
|
|
|
request = self.request_factory.get('/')
|
2015-08-19 05:57:01 +08:00
|
|
|
response = HttpResponse('Session test')
|
|
|
|
middleware = SessionMiddleware()
|
|
|
|
|
|
|
|
# Set a session key and some data.
|
|
|
|
middleware.process_request(request)
|
|
|
|
request.session['foo'] = 'bar'
|
|
|
|
# Handle the response through the middleware.
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
self.assertEqual(tuple(request.session.items()), (('foo', 'bar'),))
|
|
|
|
# A cookie should be set, along with Vary: Cookie.
|
|
|
|
self.assertIn(
|
|
|
|
'Set-Cookie: sessionid=%s' % request.session.session_key,
|
|
|
|
str(response.cookies)
|
|
|
|
)
|
|
|
|
self.assertEqual(response['Vary'], 'Cookie')
|
|
|
|
|
|
|
|
# Empty the session data.
|
|
|
|
del request.session['foo']
|
|
|
|
# Handle the response through the middleware.
|
|
|
|
response = HttpResponse('Session test')
|
|
|
|
response = middleware.process_response(request, response)
|
|
|
|
self.assertEqual(dict(request.session.values()), {})
|
|
|
|
session = Session.objects.get(session_key=request.session.session_key)
|
|
|
|
self.assertEqual(session.get_decoded(), {})
|
|
|
|
# While the session is empty, it hasn't been flushed so a cookie should
|
|
|
|
# still be set, along with Vary: Cookie.
|
|
|
|
self.assertGreater(len(request.session.session_key), 8)
|
|
|
|
self.assertIn(
|
|
|
|
'Set-Cookie: sessionid=%s' % request.session.session_key,
|
|
|
|
str(response.cookies)
|
|
|
|
)
|
|
|
|
self.assertEqual(response['Vary'], 'Cookie')
|
|
|
|
|
2012-03-23 13:31:11 +08:00
|
|
|
|
2015-01-28 22:05:47 +08:00
|
|
|
# Don't need DB flushing for these tests, so can use unittest.TestCase as base class
|
|
|
|
class CookieSessionTests(SessionTestsMixin, unittest.TestCase):
|
2011-06-27 01:00:24 +08:00
|
|
|
|
|
|
|
backend = CookieSession
|
|
|
|
|
|
|
|
def test_save(self):
|
|
|
|
"""
|
|
|
|
This test tested exists() in the other session backends, but that
|
|
|
|
doesn't make sense for us.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_cycle(self):
|
|
|
|
"""
|
|
|
|
This test tested cycle_key() which would create a new session
|
|
|
|
key for the same session data. But we can't invalidate previously
|
|
|
|
signed cookies (other than letting them expire naturally) so
|
2011-12-18 01:37:24 +08:00
|
|
|
testing for this behavior is meaningless.
|
2011-06-27 01:00:24 +08:00
|
|
|
"""
|
|
|
|
pass
|
2012-10-28 23:51:51 +08:00
|
|
|
|
|
|
|
@unittest.expectedFailure
|
|
|
|
def test_actual_expiry(self):
|
|
|
|
# The cookie backend doesn't handle non-default expiry dates, see #19201
|
2017-01-21 21:13:44 +08:00
|
|
|
super().test_actual_expiry()
|
2015-03-12 01:46:39 +08:00
|
|
|
|
|
|
|
def test_unpickling_exception(self):
|
|
|
|
# signed_cookies backend should handle unpickle exceptions gracefully
|
|
|
|
# by creating a new session
|
|
|
|
self.assertEqual(self.session.serializer, JSONSerializer)
|
|
|
|
self.session.save()
|
|
|
|
|
|
|
|
self.session.serializer = PickleSerializer
|
|
|
|
self.session.load()
|
2016-02-26 09:04:03 +08:00
|
|
|
|
|
|
|
@unittest.skip("Cookie backend doesn't have an external store to create records in.")
|
|
|
|
def test_session_load_does_not_create_record(self):
|
|
|
|
pass
|
2016-01-09 00:08:08 +08:00
|
|
|
|
|
|
|
@unittest.skip("CookieSession is stored in the client and there is no way to query it.")
|
|
|
|
def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self):
|
|
|
|
pass
|