2013-05-16 07:14:28 +08:00
|
|
|
import base64
|
2012-09-09 04:30:11 +08:00
|
|
|
from datetime import timedelta
|
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
|
2010-10-11 20:55:17 +08:00
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.contrib.sessions.backends.db import SessionStore as DatabaseSession
|
|
|
|
from django.contrib.sessions.backends.cache import SessionStore as CacheSession
|
|
|
|
from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession
|
|
|
|
from django.contrib.sessions.backends.file import SessionStore as FileSession
|
2011-06-27 03:22:53 +08:00
|
|
|
from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
|
2010-08-05 19:49:58 +08:00
|
|
|
from django.contrib.sessions.models import Session
|
2010-11-26 21:30:50 +08:00
|
|
|
from django.contrib.sessions.middleware import SessionMiddleware
|
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
|
2012-10-28 05:12:08 +08:00
|
|
|
from django.core import management
|
2013-05-16 07:14:28 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2010-11-26 21:30:50 +08:00
|
|
|
from django.http import HttpResponse
|
2014-12-22 04:19:05 +08:00
|
|
|
from django.test import TestCase, RequestFactory, ignore_warnings, override_settings
|
2013-12-23 23:01:13 +08:00
|
|
|
from django.test.utils import patch_logger
|
2012-07-21 03:14:27 +08:00
|
|
|
from django.utils import six
|
2011-11-20 18:33:44 +08:00
|
|
|
from django.utils import timezone
|
2014-07-25 04:24:01 +08:00
|
|
|
from django.utils.encoding import force_text
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2013-05-16 07:14:28 +08:00
|
|
|
from django.contrib.sessions.exceptions import InvalidSessionKey
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
class SessionTestsMixin(object):
|
|
|
|
# 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):
|
|
|
|
self.assertFalse(self.session.modified)
|
|
|
|
self.assertFalse(self.session.accessed)
|
|
|
|
|
|
|
|
def test_get_empty(self):
|
|
|
|
self.assertEqual(self.session.get('cat'), None)
|
|
|
|
|
|
|
|
def test_store(self):
|
|
|
|
self.session['cat'] = "dog"
|
|
|
|
self.assertTrue(self.session.modified)
|
|
|
|
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')
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertTrue(self.session.modified)
|
|
|
|
self.assertEqual(self.session.get('some key'), None)
|
|
|
|
|
|
|
|
def test_pop_default(self):
|
|
|
|
self.assertEqual(self.session.pop('some key', 'does not exist'),
|
|
|
|
'does not exist')
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertFalse(self.session.modified)
|
|
|
|
|
|
|
|
def test_setdefault(self):
|
|
|
|
self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar')
|
|
|
|
self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar')
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertTrue(self.session.modified)
|
|
|
|
|
|
|
|
def test_update(self):
|
|
|
|
self.session.update({'update key': 1})
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertTrue(self.session.modified)
|
|
|
|
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)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertFalse(self.session.modified)
|
|
|
|
|
|
|
|
def test_values(self):
|
2012-07-21 03:14:27 +08:00
|
|
|
self.assertEqual(list(self.session.values()), [])
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.session['some key'] = 1
|
2012-07-21 03:14:27 +08:00
|
|
|
self.assertEqual(list(self.session.values()), [1])
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def test_iterkeys(self):
|
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2012-07-21 03:14:27 +08:00
|
|
|
i = six.iterkeys(self.session)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertTrue(hasattr(i, '__iter__'))
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertFalse(self.session.modified)
|
|
|
|
self.assertEqual(list(i), ['x'])
|
|
|
|
|
2011-02-01 02:37:28 +08:00
|
|
|
def test_itervalues(self):
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2012-07-21 03:14:27 +08:00
|
|
|
i = six.itervalues(self.session)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertTrue(hasattr(i, '__iter__'))
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertFalse(self.session.modified)
|
|
|
|
self.assertEqual(list(i), [1])
|
|
|
|
|
|
|
|
def test_iteritems(self):
|
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2012-07-21 03:14:27 +08:00
|
|
|
i = six.iteritems(self.session)
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertTrue(hasattr(i, '__iter__'))
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertFalse(self.session.modified)
|
2012-03-23 13:31:11 +08:00
|
|
|
self.assertEqual(list(i), [('x', 1)])
|
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()), [])
|
2010-08-05 19:49:58 +08:00
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
self.assertTrue(self.session.modified)
|
|
|
|
|
|
|
|
def test_save(self):
|
2013-10-19 06:49:24 +08:00
|
|
|
if (hasattr(self.session, '_cache') and 'DummyCache' in
|
2013-11-26 17:43:46 +08:00
|
|
|
settings.CACHES[settings.SESSION_CACHE_ALIAS]['BACKEND']):
|
2012-09-21 19:12:51 +08:00
|
|
|
raise unittest.SkipTest("Session saving tests require a real cache backend")
|
2010-08-05 19:49:58 +08:00
|
|
|
self.session.save()
|
|
|
|
self.assertTrue(self.session.exists(self.session.session_key))
|
|
|
|
|
|
|
|
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)
|
|
|
|
self.assertFalse(self.session.exists(self.session.session_key))
|
|
|
|
|
|
|
|
def test_flush(self):
|
|
|
|
self.session['foo'] = 'bar'
|
|
|
|
self.session.save()
|
|
|
|
prev_key = self.session.session_key
|
|
|
|
self.session.flush()
|
|
|
|
self.assertFalse(self.session.exists(prev_key))
|
|
|
|
self.assertNotEqual(self.session.session_key, prev_key)
|
|
|
|
self.assertTrue(self.session.modified)
|
|
|
|
self.assertTrue(self.session.accessed)
|
|
|
|
|
|
|
|
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()
|
|
|
|
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
|
|
|
|
|
|
|
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')
|
2011-10-05 13:21:47 +08:00
|
|
|
try:
|
|
|
|
session.save()
|
|
|
|
except AttributeError:
|
2014-09-04 20:15:09 +08:00
|
|
|
self.fail(
|
|
|
|
"The session object did not save properly. "
|
|
|
|
"Middleware may be saving cache items without namespaces."
|
|
|
|
)
|
2011-01-17 22:03:19 +08:00
|
|
|
self.assertNotEqual(session.session_key, '1')
|
|
|
|
self.assertEqual(session.get('cat'), 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')
|
2010-08-05 19:49:58 +08:00
|
|
|
|
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()
|
|
|
|
self.assertRaises(AttributeError, set_session_key, self.session)
|
|
|
|
|
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)
|
|
|
|
self.assertFalse(self.session.get_expire_at_browser_close())
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(0)
|
|
|
|
self.assertTrue(self.session.get_expire_at_browser_close())
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(None)
|
|
|
|
self.assertFalse(self.session.get_expire_at_browser_close())
|
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)
|
|
|
|
self.assertFalse(self.session.get_expire_at_browser_close())
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(0)
|
|
|
|
self.assertTrue(self.session.get_expire_at_browser_close())
|
2010-08-05 19:49:58 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
self.session.set_expiry(None)
|
|
|
|
self.assertTrue(self.session.get_expire_at_browser_close())
|
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):
|
|
|
|
bad_encode = base64.b64encode(b'flaskdj:alkdjf')
|
|
|
|
with patch_logger('django.security.SuspiciousSession', 'warning') as calls:
|
|
|
|
self.assertEqual({}, self.session.decode(bad_encode))
|
|
|
|
# check that the failed decode is logged
|
|
|
|
self.assertEqual(len(calls), 1)
|
2014-10-28 18:02:56 +08:00
|
|
|
self.assertIn('corrupted', calls[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
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
class DatabaseSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
backend = DatabaseSession
|
|
|
|
|
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
|
|
|
|
s = Session.objects.get(session_key=session_key)
|
|
|
|
|
|
|
|
self.assertEqual(force_text(s), session_key)
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
s = Session.objects.get(session_key=self.session.session_key)
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
s = Session.objects.get(session_key=self.session.session_key)
|
|
|
|
# Change it
|
2012-03-23 13:31:11 +08:00
|
|
|
Session.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
|
|
|
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.db")
|
|
|
|
def test_clearsessions_command(self):
|
|
|
|
"""
|
|
|
|
Test clearsessions command for clearing expired sessions.
|
|
|
|
"""
|
|
|
|
self.assertEqual(0, Session.objects.count())
|
|
|
|
|
|
|
|
# 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...
|
|
|
|
self.assertEqual(2, Session.objects.count())
|
|
|
|
management.call_command('clearsessions')
|
|
|
|
# ... and one is deleted.
|
|
|
|
self.assertEqual(1, Session.objects.count())
|
|
|
|
|
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
|
|
|
|
|
|
|
|
2010-08-05 19:49:58 +08:00
|
|
|
class CacheDBSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
backend = CacheDBSession
|
|
|
|
|
2012-10-31 04:59:23 +08:00
|
|
|
@unittest.skipIf('DummyCache' in
|
|
|
|
settings.CACHES[settings.SESSION_CACHE_ALIAS]['BACKEND'],
|
2012-09-21 19:12:51 +08:00
|
|
|
"Session saving tests require a real cache backend")
|
2011-11-28 02:36:03 +08:00
|
|
|
def test_exists_searches_cache_first(self):
|
|
|
|
self.session.save()
|
|
|
|
with self.assertNumQueries(0):
|
|
|
|
self.assertTrue(self.session.exists(self.session.session_key))
|
|
|
|
|
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.
|
2013-08-30 12:03:23 +08:00
|
|
|
self.assertRaises(InvalidCacheBackendError, self.backend)
|
|
|
|
|
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
|
2012-10-28 03:59:35 +08:00
|
|
|
super(FileSessionTests, self).setUp()
|
2010-08-05 19:49:58 +08:00
|
|
|
|
|
|
|
def tearDown(self):
|
2012-10-28 03:59:35 +08:00
|
|
|
super(FileSessionTests, self).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(
|
|
|
|
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
|
|
|
|
self.assertRaises(ImproperlyConfigured, self.backend)
|
|
|
|
|
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
|
|
|
|
# a SuspiciousOperation in the same way as an IOError - by creating
|
|
|
|
# a new session, making it unclear whether the slashes were detected.
|
2013-05-16 07:14:28 +08:00
|
|
|
self.assertRaises(InvalidSessionKey,
|
2013-05-19 21:25:49 +08:00
|
|
|
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
|
2013-05-16 07:14:28 +08:00
|
|
|
self.assertRaises(InvalidSessionKey,
|
2013-05-19 21:25:49 +08:00
|
|
|
self.backend()._key_to_file, "a/b/c")
|
2011-02-09 10:13:24 +08:00
|
|
|
|
2012-10-28 05:12:08 +08:00
|
|
|
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.file")
|
|
|
|
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():
|
|
|
|
return len([session_file for session_file in os.listdir(storage_path)
|
2013-12-13 04:23:24 +08:00
|
|
|
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()
|
|
|
|
|
|
|
|
# Two sessions are in the filesystem before clearsessions...
|
|
|
|
self.assertEqual(2, count_sessions())
|
|
|
|
management.call_command('clearsessions')
|
|
|
|
# ... and one is deleted.
|
|
|
|
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()
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertNotEqual(caches['default'].get(self.session.cache_key), None)
|
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()
|
2013-10-19 06:49:24 +08:00
|
|
|
self.assertEqual(caches['default'].get(self.session.cache_key), None)
|
|
|
|
self.assertNotEqual(caches['sessions'].get(self.session.cache_key), None)
|
2012-10-31 04:59:23 +08:00
|
|
|
|
2010-11-26 21:30:50 +08:00
|
|
|
|
|
|
|
class SessionMiddlewareTests(unittest.TestCase):
|
|
|
|
|
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):
|
|
|
|
request = RequestFactory().get('/')
|
|
|
|
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)
|
2011-11-22 06:03:03 +08:00
|
|
|
self.assertTrue(
|
|
|
|
response.cookies[settings.SESSION_COOKIE_NAME]['secure'])
|
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):
|
|
|
|
request = RequestFactory().get('/')
|
|
|
|
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)
|
2011-11-22 06:03:03 +08:00
|
|
|
self.assertTrue(
|
|
|
|
response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])
|
2011-11-28 01:52:24 +08:00
|
|
|
self.assertIn('httponly',
|
2011-11-22 06:03:03 +08:00
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME]))
|
|
|
|
|
|
|
|
@override_settings(SESSION_COOKIE_HTTPONLY=False)
|
|
|
|
def test_no_httponly_session_cookie(self):
|
|
|
|
request = RequestFactory().get('/')
|
|
|
|
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)
|
2012-03-31 16:24:29 +08:00
|
|
|
self.assertFalse(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])
|
2011-11-22 09:10:00 +08:00
|
|
|
|
2011-11-28 01:52:24 +08:00
|
|
|
self.assertNotIn('httponly',
|
2011-11-22 09:10:00 +08:00
|
|
|
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):
|
|
|
|
request = RequestFactory().get('/')
|
|
|
|
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)
|
|
|
|
|
|
|
|
# Check that the value wasn't saved above.
|
|
|
|
self.assertNotIn('hello', request.session.load())
|
|
|
|
|
2013-08-19 13:36:36 +08:00
|
|
|
def test_session_delete_on_end(self):
|
|
|
|
request = RequestFactory().get('/')
|
|
|
|
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)
|
|
|
|
|
|
|
|
# Check that the cookie was deleted, not recreated.
|
|
|
|
# A deleted cookie header looks like:
|
|
|
|
# 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(
|
2014-11-27 08:41:27 +08:00
|
|
|
'Set-Cookie: {}=; expires=Thu, 01-Jan-1970 00:00:00 GMT; '
|
2014-09-04 20:15:09 +08:00
|
|
|
'Max-Age=0; Path=/'.format(settings.SESSION_COOKIE_NAME),
|
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
2013-08-19 13:36:36 +08:00
|
|
|
|
2012-03-23 13:31:11 +08:00
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
class CookieSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
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
|
|
|
|
super(CookieSessionTests, self).test_actual_expiry()
|