2013-05-15 23:14:28 +00:00
|
|
|
import base64
|
2012-10-27 21:12:08 +00:00
|
|
|
import os
|
2010-10-11 12:55:17 +00:00
|
|
|
import shutil
|
2012-03-23 05:31:11 +00:00
|
|
|
import string
|
2010-10-11 12:55:17 +00:00
|
|
|
import tempfile
|
2013-07-01 12:22:27 +00:00
|
|
|
import unittest
|
2015-01-28 12:35:27 +00:00
|
|
|
from datetime import timedelta
|
2017-01-07 11:11:46 +00:00
|
|
|
from http import cookies
|
2019-11-07 09:26:22 +00:00
|
|
|
from pathlib import Path
|
2010-10-11 12:55:17 +00:00
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
from django.conf import settings
|
2016-01-08 16:08:08 +00:00
|
|
|
from django.contrib.sessions.backends.base import UpdateError
|
2010-08-05 11:49:58 +00:00
|
|
|
from django.contrib.sessions.backends.cache import SessionStore as CacheSession
|
2017-06-01 17:23:48 +00:00
|
|
|
from django.contrib.sessions.backends.cached_db import (
|
|
|
|
SessionStore as CacheDBSession,
|
|
|
|
)
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.contrib.sessions.backends.db import SessionStore as DatabaseSession
|
2010-08-05 11:49:58 +00:00
|
|
|
from django.contrib.sessions.backends.file import SessionStore as FileSession
|
2017-06-01 17:23:48 +00:00
|
|
|
from django.contrib.sessions.backends.signed_cookies import (
|
|
|
|
SessionStore as CookieSession,
|
|
|
|
)
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.contrib.sessions.exceptions import InvalidSessionKey
|
2010-11-26 13:30:50 +00:00
|
|
|
from django.contrib.sessions.middleware import SessionMiddleware
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.contrib.sessions.models import Session
|
2015-03-11 17:46:39 +00:00
|
|
|
from django.contrib.sessions.serializers import (
|
|
|
|
JSONSerializer, PickleSerializer,
|
|
|
|
)
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.core import management
|
2013-10-18 22:49:24 +00:00
|
|
|
from django.core.cache import caches
|
2013-08-30 04:03:23 +00:00
|
|
|
from django.core.cache.backends.base import InvalidCacheBackendError
|
2016-10-25 11:23:14 +00:00
|
|
|
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
|
2010-11-26 13:30:50 +00:00
|
|
|
from django.http import HttpResponse
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.test import (
|
2020-08-07 19:42:39 +00:00
|
|
|
RequestFactory, SimpleTestCase, TestCase, ignore_warnings,
|
|
|
|
override_settings,
|
2015-01-28 12:35:27 +00:00
|
|
|
)
|
2017-01-07 11:11:46 +00:00
|
|
|
from django.utils import timezone
|
2020-08-07 19:42:39 +00:00
|
|
|
from django.utils.deprecation import RemovedInDjango40Warning
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2016-02-04 16:47:20 +00:00
|
|
|
from .models import SessionStore as CustomDatabaseSession
|
2014-05-16 16:18:34 +00:00
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2017-01-19 07:39:46 +00:00
|
|
|
class SessionTestsMixin:
|
2010-08-05 11:49:58 +00: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 05:31:11 +00:00
|
|
|
backend = None # subclasses must specify
|
2010-08-05 11:49:58 +00: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 00:21:39 +00:00
|
|
|
self.assertIs(self.session.modified, False)
|
|
|
|
self.assertIs(self.session.accessed, False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_get_empty(self):
|
2016-06-16 18:19:18 +00:00
|
|
|
self.assertIsNone(self.session.get('cat'))
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_store(self):
|
|
|
|
self.session['cat'] = "dog"
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 11:49:58 +00: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 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2016-06-16 18:19:18 +00:00
|
|
|
self.assertIsNone(self.session.get('some key'))
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_pop_default(self):
|
|
|
|
self.assertEqual(self.session.pop('some key', 'does not exist'),
|
|
|
|
'does not exist')
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2016-04-20 15:04:58 +00: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 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2016-04-20 15:04:58 +00:00
|
|
|
|
2016-04-20 08:36:59 +00:00
|
|
|
def test_pop_no_default_keyerror_raised(self):
|
|
|
|
with self.assertRaises(KeyError):
|
|
|
|
self.session.pop('some key')
|
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
def test_setdefault(self):
|
|
|
|
self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar')
|
|
|
|
self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar')
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_update(self):
|
|
|
|
self.session.update({'update key': 1})
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 11:49:58 +00: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-27 17:18:03 +00:00
|
|
|
self.assertIn('some key', self.session)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_values(self):
|
2012-07-20 19:14:27 +00:00
|
|
|
self.assertEqual(list(self.session.values()), [])
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session['some key'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2017-01-19 18:16:22 +00:00
|
|
|
self.assertEqual(list(self.session.values()), [1])
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2017-01-19 18:16:22 +00:00
|
|
|
def test_keys(self):
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2017-01-19 18:16:22 +00:00
|
|
|
self.assertEqual(list(self.session.keys()), ['x'])
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2017-01-19 18:16:22 +00:00
|
|
|
def test_items(self):
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2017-01-19 18:16:22 +00:00
|
|
|
self.assertEqual(list(self.session.items()), [('x', 1)])
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_clear(self):
|
|
|
|
self.session['x'] = 1
|
|
|
|
self.session.modified = False
|
|
|
|
self.session.accessed = False
|
2012-07-20 19:14:27 +00:00
|
|
|
self.assertEqual(list(self.session.items()), [('x', 1)])
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session.clear()
|
2012-07-20 19:14:27 +00:00
|
|
|
self.assertEqual(list(self.session.items()), [])
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.accessed, True)
|
|
|
|
self.assertIs(self.session.modified, True)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_save(self):
|
|
|
|
self.session.save()
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.exists(self.session.session_key), True)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_delete(self):
|
2011-11-27 17:52:24 +00:00
|
|
|
self.session.save()
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session.delete(self.session.session_key)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.exists(self.session.session_key), False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_flush(self):
|
|
|
|
self.session['foo'] = 'bar'
|
|
|
|
self.session.save()
|
|
|
|
prev_key = self.session.session_key
|
|
|
|
self.session.flush()
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.exists(prev_key), False)
|
2010-08-05 11:49:58 +00:00
|
|
|
self.assertNotEqual(self.session.session_key, prev_key)
|
2015-05-11 13:58:43 +00:00
|
|
|
self.assertIsNone(self.session.session_key)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.modified, True)
|
|
|
|
self.assertIs(self.session.accessed, True)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def test_cycle(self):
|
|
|
|
self.session['a'], self.session['b'] = 'c', 'd'
|
|
|
|
self.session.save()
|
|
|
|
prev_key = self.session.session_key
|
2012-07-20 19:14:27 +00:00
|
|
|
prev_data = list(self.session.items())
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session.cycle_key()
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.exists(prev_key), False)
|
2010-08-05 11:49:58 +00:00
|
|
|
self.assertNotEqual(self.session.session_key, prev_key)
|
2012-07-20 19:14:27 +00:00
|
|
|
self.assertEqual(list(self.session.items()), prev_data)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2016-08-08 17:01:25 +00:00
|
|
|
def test_cycle_with_no_session_cache(self):
|
2017-04-12 00:35:17 +00:00
|
|
|
self.session['a'], self.session['b'] = 'c', 'd'
|
|
|
|
self.session.save()
|
2017-04-18 15:56:59 +00:00
|
|
|
prev_data = self.session.items()
|
2017-04-12 00:35:17 +00:00
|
|
|
self.session = self.backend(self.session.session_key)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(hasattr(self.session, '_session_cache'), False)
|
2016-08-08 17:01:25 +00:00
|
|
|
self.session.cycle_key()
|
2017-04-18 15:56:59 +00:00
|
|
|
self.assertCountEqual(self.session.items(), prev_data)
|
2016-08-08 17:01:25 +00:00
|
|
|
|
2015-06-10 21:45:20 +00:00
|
|
|
def test_save_doesnt_clear_data(self):
|
|
|
|
self.session['a'] = 'b'
|
|
|
|
self.session.save()
|
|
|
|
self.assertEqual(self.session['a'], 'b')
|
|
|
|
|
2010-08-05 11:49:58 +00: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 14:03:19 +00:00
|
|
|
try:
|
|
|
|
session = self.backend('1')
|
2016-06-28 15:21:26 +00:00
|
|
|
session.save()
|
2011-01-17 14:03:19 +00:00
|
|
|
self.assertNotEqual(session.session_key, '1')
|
2016-06-16 18:19:18 +00:00
|
|
|
self.assertIsNone(session.get('cat'))
|
2011-01-17 14:03:19 +00: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 11:49:58 +00:00
|
|
|
|
2015-06-05 12:48:41 +00: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-27 17:52:24 +00: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 11:26:39 +00:00
|
|
|
with self.assertRaises(AttributeError):
|
|
|
|
set_session_key(self.session)
|
2011-11-27 17:52:24 +00:00
|
|
|
|
2010-08-05 11:49:58 +00: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-27 19:32:50 +00:00
|
|
|
modification = timezone.now()
|
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
self.session.set_expiry(10)
|
|
|
|
|
2012-10-27 19:32:50 +00: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 11:49:58 +00:00
|
|
|
|
|
|
|
def test_custom_expiry_timedelta(self):
|
2012-10-27 19:32:50 +00: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 11:49:58 +00:00
|
|
|
|
2012-10-27 19:32:50 +00:00
|
|
|
age = self.session.get_expiry_age(modification=modification)
|
|
|
|
self.assertEqual(age, 10)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2011-01-31 18:37:28 +00:00
|
|
|
def test_custom_expiry_datetime(self):
|
2012-10-27 19:32:50 +00: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 11:49:58 +00:00
|
|
|
|
2012-10-27 19:32:50 +00:00
|
|
|
age = self.session.get_expiry_age(modification=modification)
|
|
|
|
self.assertEqual(age, 10)
|
2010-08-05 11:49:58 +00: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-26 17:00:24 +00:00
|
|
|
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False):
|
|
|
|
self.session.set_expiry(10)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
self.session.set_expiry(0)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), True)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
self.session.set_expiry(None)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True):
|
|
|
|
self.session.set_expiry(10)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), False)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
self.session.set_expiry(0)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), True)
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
self.session.set_expiry(None)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.get_expire_at_browser_close(), True)
|
2010-08-05 11:49:58 +00: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-14 20:54:30 +00: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)
|
|
|
|
|
2020-02-15 11:20:37 +00:00
|
|
|
@override_settings(SECRET_KEY='django_tests_secret_key')
|
|
|
|
def test_decode_legacy(self):
|
|
|
|
# RemovedInDjango40Warning: pre-Django 3.1 sessions will be invalid.
|
|
|
|
legacy_encoded = (
|
|
|
|
'OWUzNTNmNWQxNTBjOWExZmM4MmQ3NzNhMDRmMjU4NmYwNDUyNGI2NDp7ImEgdGVzd'
|
|
|
|
'CBrZXkiOiJhIHRlc3QgdmFsdWUifQ=='
|
|
|
|
)
|
|
|
|
self.assertEqual(
|
|
|
|
self.session.decode(legacy_encoded),
|
|
|
|
{'a test key': 'a test value'},
|
|
|
|
)
|
|
|
|
|
2020-08-07 19:42:39 +00:00
|
|
|
@ignore_warnings(category=RemovedInDjango40Warning)
|
|
|
|
def test_default_hashing_algorith_legacy_decode(self):
|
|
|
|
with self.settings(DEFAULT_HASHING_ALGORITHM='sha1'):
|
|
|
|
data = {'a test key': 'a test value'}
|
|
|
|
encoded = self.session.encode(data)
|
|
|
|
self.assertEqual(self.session._legacy_decode(encoded), data)
|
|
|
|
|
2013-05-15 23:14:28 +00:00
|
|
|
def test_decode_failure_logged_to_security(self):
|
2020-08-19 10:06:00 +00:00
|
|
|
tests = [
|
|
|
|
base64.b64encode(b'flaskdj:alkdjf').decode('ascii'),
|
|
|
|
'bad:encoded:value',
|
|
|
|
]
|
|
|
|
for encoded in tests:
|
|
|
|
with self.subTest(encoded=encoded):
|
|
|
|
with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm:
|
|
|
|
self.assertEqual(self.session.decode(encoded), {})
|
|
|
|
# The failed decode is logged.
|
|
|
|
self.assertIn('Session data corrupted', cm.output[0])
|
2013-05-15 23:14:28 +00:00
|
|
|
|
2012-10-27 17:18:03 +00:00
|
|
|
def test_actual_expiry(self):
|
2013-08-22 00:12:19 +00: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-27 17:18:03 +00:00
|
|
|
|
2015-06-10 21:45:20 +00: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 14:09:28 +00:00
|
|
|
self.assertIsNone(session.session_key)
|
|
|
|
self.assertIs(session.exists(session.session_key), False)
|
2015-06-10 21:45:20 +00:00
|
|
|
# provided unknown key was cycled, not reused
|
|
|
|
self.assertNotEqual(session.session_key, 'someunknownkey')
|
|
|
|
|
2016-01-08 16:08:08 +00: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 11:49:58 +00:00
|
|
|
|
|
|
|
class DatabaseSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
backend = DatabaseSession
|
2014-05-16 16:18:34 +00:00
|
|
|
session_engine = 'django.contrib.sessions.backends.db'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def model(self):
|
|
|
|
return self.backend.get_model_class()
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2014-07-24 20:24:01 +00: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-16 16:18:34 +00:00
|
|
|
s = self.model.objects.get(session_key=session_key)
|
2014-07-24 20:24:01 +00:00
|
|
|
|
2017-01-24 11:22:42 +00:00
|
|
|
self.assertEqual(str(s), session_key)
|
2014-07-24 20:24:01 +00:00
|
|
|
|
2010-11-14 22:23:46 +00: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-16 16:18:34 +00:00
|
|
|
s = self.model.objects.get(session_key=self.session.session_key)
|
2010-11-14 22:23:46 +00: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-16 16:18:34 +00:00
|
|
|
s = self.model.objects.get(session_key=self.session.session_key)
|
2010-11-14 22:23:46 +00:00
|
|
|
# Change it
|
2014-05-16 16:18:34 +00:00
|
|
|
self.model.objects.save(s.session_key, {'y': 2}, s.expire_date)
|
2010-11-14 22:23:46 +00:00
|
|
|
# Clear cache, so that it will be retrieved from DB
|
|
|
|
del self.session._session_cache
|
|
|
|
self.assertEqual(self.session['y'], 2)
|
|
|
|
|
2012-10-27 21:12:08 +00:00
|
|
|
def test_clearsessions_command(self):
|
|
|
|
"""
|
|
|
|
Test clearsessions command for clearing expired sessions.
|
|
|
|
"""
|
2014-05-16 16:18:34 +00:00
|
|
|
self.assertEqual(0, self.model.objects.count())
|
2012-10-27 21:12:08 +00: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-16 16:18:34 +00:00
|
|
|
self.assertEqual(2, self.model.objects.count())
|
|
|
|
with override_settings(SESSION_ENGINE=self.session_engine):
|
|
|
|
management.call_command('clearsessions')
|
2012-10-27 21:12:08 +00:00
|
|
|
# ... and one is deleted.
|
2014-05-16 16:18:34 +00:00
|
|
|
self.assertEqual(1, self.model.objects.count())
|
2012-10-27 21:12:08 +00:00
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2012-03-30 09:08:29 +00:00
|
|
|
@override_settings(USE_TZ=True)
|
|
|
|
class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests):
|
|
|
|
pass
|
2011-11-20 10:33:44 +00:00
|
|
|
|
|
|
|
|
2014-05-16 16:18:34 +00:00
|
|
|
class CustomDatabaseSessionTests(DatabaseSessionTests):
|
|
|
|
backend = CustomDatabaseSession
|
2016-02-04 16:47:20 +00:00
|
|
|
session_engine = 'sessions_tests.models'
|
2019-05-19 20:15:45 +00:00
|
|
|
custom_session_cookie_age = 60 * 60 * 24 # One day.
|
2014-05-16 16:18:34 +00: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-16 18:19:18 +00:00
|
|
|
self.assertIsNone(s.account_id)
|
2014-05-16 16:18:34 +00:00
|
|
|
|
2019-05-19 20:15:45 +00: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(), self.custom_session_cookie_age)
|
|
|
|
|
|
|
|
def test_default_expiry(self):
|
|
|
|
self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age)
|
|
|
|
self.session.set_expiry(0)
|
|
|
|
self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age)
|
|
|
|
|
2014-05-16 16:18:34 +00:00
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
class CacheDBSessionTests(SessionTestsMixin, TestCase):
|
|
|
|
|
|
|
|
backend = CacheDBSession
|
|
|
|
|
2011-11-27 18:36:03 +00:00
|
|
|
def test_exists_searches_cache_first(self):
|
|
|
|
self.session.save()
|
|
|
|
with self.assertNumQueries(0):
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(self.session.exists(self.session.session_key), True)
|
2011-11-27 18:36:03 +00:00
|
|
|
|
2014-12-21 20:19:05 +00:00
|
|
|
# Some backends might issue a warning
|
|
|
|
@ignore_warnings(module="django.core.cache.backends.base")
|
2012-03-23 05:31:11 +00:00
|
|
|
def test_load_overlong_key(self):
|
2014-12-21 20:19:05 +00:00
|
|
|
self.session._session_key = (string.ascii_letters + string.digits) * 20
|
|
|
|
self.assertEqual(self.session.load(), {})
|
2012-03-23 05:31:11 +00:00
|
|
|
|
2013-08-30 04:03:23 +00:00
|
|
|
@override_settings(SESSION_CACHE_ALIAS='sessions')
|
|
|
|
def test_non_default_cache(self):
|
2013-11-02 21:02:56 +00:00
|
|
|
# 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS.
|
2016-01-17 11:26:39 +00:00
|
|
|
with self.assertRaises(InvalidCacheBackendError):
|
|
|
|
self.backend()
|
2013-08-30 04:03:23 +00:00
|
|
|
|
2011-11-20 10:33:44 +00:00
|
|
|
|
2012-03-30 09:08:29 +00:00
|
|
|
@override_settings(USE_TZ=True)
|
|
|
|
class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests):
|
|
|
|
pass
|
2011-11-20 10:33:44 +00:00
|
|
|
|
|
|
|
|
2020-08-07 19:42:39 +00:00
|
|
|
class FileSessionTests(SessionTestsMixin, SimpleTestCase):
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
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
|
2019-11-07 09:26:22 +00:00
|
|
|
self.temp_session_store = settings.SESSION_FILE_PATH = self.mkdtemp()
|
2012-10-27 21:12:08 +00:00
|
|
|
# Reset the file session backend's internal caches
|
|
|
|
if hasattr(self.backend, '_storage_path'):
|
|
|
|
del self.backend._storage_path
|
2017-01-21 13:13:44 +00:00
|
|
|
super().setUp()
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
def tearDown(self):
|
2017-01-21 13:13:44 +00:00
|
|
|
super().tearDown()
|
2010-08-05 11:49:58 +00:00
|
|
|
settings.SESSION_FILE_PATH = self.original_session_file_path
|
|
|
|
shutil.rmtree(self.temp_session_store)
|
|
|
|
|
2019-11-07 09:26:22 +00:00
|
|
|
def mkdtemp(self):
|
|
|
|
return tempfile.mkdtemp()
|
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
@override_settings(
|
2018-03-16 09:54:34 +00:00
|
|
|
SESSION_FILE_PATH='/if/this/directory/exists/you/have/a/weird/computer',
|
|
|
|
)
|
2010-08-05 11:49:58 +00:00
|
|
|
def test_configuration_check(self):
|
2012-10-27 21:12:08 +00:00
|
|
|
del self.backend._storage_path
|
2010-08-05 11:49:58 +00:00
|
|
|
# Make sure the file backend checks for a good storage dir
|
2016-01-17 11:26:39 +00:00
|
|
|
with self.assertRaises(ImproperlyConfigured):
|
|
|
|
self.backend()
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2013-05-19 13:25:49 +00: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 15:01:35 +00:00
|
|
|
# a SuspiciousOperation in the same way as an OSError - by creating
|
2013-05-19 13:25:49 +00:00
|
|
|
# a new session, making it unclear whether the slashes were detected.
|
2016-01-17 11:26:39 +00:00
|
|
|
with self.assertRaises(InvalidSessionKey):
|
|
|
|
self.backend()._key_to_file("a\\b\\c")
|
2011-02-09 02:13:24 +00:00
|
|
|
|
|
|
|
def test_invalid_key_forwardslash(self):
|
|
|
|
# Ensure we don't allow directory-traversal
|
2016-01-17 11:26:39 +00:00
|
|
|
with self.assertRaises(InvalidSessionKey):
|
|
|
|
self.backend()._key_to_file("a/b/c")
|
2011-02-09 02:13:24 +00:00
|
|
|
|
2015-03-23 11:52:17 +00:00
|
|
|
@override_settings(
|
|
|
|
SESSION_ENGINE="django.contrib.sessions.backends.file",
|
|
|
|
SESSION_COOKIE_AGE=0,
|
|
|
|
)
|
2012-10-27 21:12:08 +00: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 02:04:45 +00:00
|
|
|
return len([
|
|
|
|
session_file for session_file in os.listdir(storage_path)
|
|
|
|
if session_file.startswith(file_prefix)
|
|
|
|
])
|
2012-10-27 21:12:08 +00: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 11:52:17 +00: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-27 21:12:08 +00:00
|
|
|
management.call_command('clearsessions')
|
2015-03-23 11:52:17 +00:00
|
|
|
# ... and two are deleted.
|
2012-10-27 21:12:08 +00:00
|
|
|
self.assertEqual(1, count_sessions())
|
|
|
|
|
2010-08-05 11:49:58 +00:00
|
|
|
|
2019-11-07 09:26:22 +00:00
|
|
|
class FileSessionPathLibTests(FileSessionTests):
|
|
|
|
def mkdtemp(self):
|
|
|
|
tmp_dir = super().mkdtemp()
|
|
|
|
return Path(tmp_dir)
|
|
|
|
|
|
|
|
|
2020-08-07 19:42:39 +00:00
|
|
|
class CacheSessionTests(SessionTestsMixin, SimpleTestCase):
|
2010-08-05 11:49:58 +00:00
|
|
|
|
|
|
|
backend = CacheSession
|
2010-11-26 13:30:50 +00:00
|
|
|
|
2014-12-21 20:19:05 +00:00
|
|
|
# Some backends might issue a warning
|
|
|
|
@ignore_warnings(module="django.core.cache.backends.base")
|
2012-03-23 05:31:11 +00:00
|
|
|
def test_load_overlong_key(self):
|
2014-12-21 20:19:05 +00:00
|
|
|
self.session._session_key = (string.ascii_letters + string.digits) * 20
|
|
|
|
self.assertEqual(self.session.load(), {})
|
2012-03-23 05:31:11 +00:00
|
|
|
|
2012-10-30 20:59:23 +00:00
|
|
|
def test_default_cache(self):
|
|
|
|
self.session.save()
|
2016-06-16 18:19:18 +00:00
|
|
|
self.assertIsNotNone(caches['default'].get(self.session.cache_key))
|
2012-10-30 20:59:23 +00:00
|
|
|
|
|
|
|
@override_settings(CACHES={
|
|
|
|
'default': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
|
|
|
|
},
|
|
|
|
'sessions': {
|
|
|
|
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
|
2013-10-18 22:49:24 +00:00
|
|
|
'LOCATION': 'session',
|
2012-10-30 20:59:23 +00:00
|
|
|
},
|
|
|
|
}, SESSION_CACHE_ALIAS='sessions')
|
|
|
|
def test_non_default_cache(self):
|
2014-04-26 17:18:45 +00:00
|
|
|
# Re-initialize the session backend to make use of overridden settings.
|
2013-02-23 15:33:28 +00:00
|
|
|
self.session = self.backend()
|
|
|
|
|
2012-10-30 20:59:23 +00:00
|
|
|
self.session.save()
|
2016-06-16 18:19:18 +00:00
|
|
|
self.assertIsNone(caches['default'].get(self.session.cache_key))
|
|
|
|
self.assertIsNotNone(caches['sessions'].get(self.session.cache_key))
|
2012-10-30 20:59:23 +00:00
|
|
|
|
2016-04-03 22:09:10 +00: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 13:30:50 +00:00
|
|
|
|
2015-01-28 14:05:47 +00:00
|
|
|
class SessionMiddlewareTests(TestCase):
|
2018-11-26 19:01:27 +00:00
|
|
|
request_factory = RequestFactory()
|
2010-11-26 13:30:50 +00:00
|
|
|
|
2019-09-26 17:06:35 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_response_touching_session(request):
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
return HttpResponse('Session test')
|
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
@override_settings(SESSION_COOKIE_SECURE=True)
|
2010-11-26 13:30:50 +00:00
|
|
|
def test_secure_session_cookie(self):
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(self.get_response_touching_session)
|
2010-11-26 13:30:50 +00:00
|
|
|
|
|
|
|
# Handle the response through the middleware
|
2019-09-26 17:06:35 +00:00
|
|
|
response = middleware(request)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True)
|
2010-11-26 13:30:50 +00:00
|
|
|
|
2011-06-26 17:00:24 +00:00
|
|
|
@override_settings(SESSION_COOKIE_HTTPONLY=True)
|
2010-11-26 13:30:50 +00:00
|
|
|
def test_httponly_session_cookie(self):
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(self.get_response_touching_session)
|
2010-11-26 13:30:50 +00:00
|
|
|
|
|
|
|
# Handle the response through the middleware
|
2019-09-26 17:06:35 +00:00
|
|
|
response = middleware(request)
|
2017-05-04 00:21:39 +00:00
|
|
|
self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], True)
|
2016-04-08 02:04:45 +00:00
|
|
|
self.assertIn(
|
2017-01-07 11:11:46 +00:00
|
|
|
cookies.Morsel._reserved['httponly'],
|
2016-04-08 02:04:45 +00:00
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
2011-11-21 22:03:03 +00:00
|
|
|
|
2018-04-14 00:58:31 +00:00
|
|
|
@override_settings(SESSION_COOKIE_SAMESITE='Strict')
|
|
|
|
def test_samesite_session_cookie(self):
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(self.get_response_touching_session)
|
|
|
|
response = middleware(request)
|
2018-04-14 00:58:31 +00:00
|
|
|
self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict')
|
|
|
|
|
2011-11-21 22:03:03 +00:00
|
|
|
@override_settings(SESSION_COOKIE_HTTPONLY=False)
|
|
|
|
def test_no_httponly_session_cookie(self):
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(self.get_response_touching_session)
|
|
|
|
response = middleware(request)
|
2017-05-04 00:21:39 +00: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-26 17:00:24 +00:00
|
|
|
|
2012-07-05 15:09:48 +00:00
|
|
|
def test_session_save_on_500(self):
|
2019-09-26 17:06:35 +00:00
|
|
|
def response_500(requset):
|
|
|
|
response = HttpResponse('Horrible error')
|
|
|
|
response.status_code = 500
|
|
|
|
request.session['hello'] = 'world'
|
|
|
|
return response
|
2012-07-05 15:09:48 +00:00
|
|
|
|
2019-09-26 17:06:35 +00:00
|
|
|
request = self.request_factory.get('/')
|
|
|
|
SessionMiddleware(response_500)(request)
|
2012-07-05 15:09:48 +00:00
|
|
|
|
2016-10-27 07:53:39 +00:00
|
|
|
# The value wasn't saved above.
|
2012-07-05 15:09:48 +00:00
|
|
|
self.assertNotIn('hello', request.session.load())
|
|
|
|
|
2016-01-08 16:08:08 +00:00
|
|
|
def test_session_update_error_redirect(self):
|
2019-09-26 17:06:35 +00:00
|
|
|
def response_delete_session(request):
|
|
|
|
request.session = DatabaseSession()
|
|
|
|
request.session.save(must_create=True)
|
|
|
|
request.session.delete()
|
|
|
|
return HttpResponse()
|
2016-01-08 16:08:08 +00:00
|
|
|
|
2019-09-26 17:06:35 +00:00
|
|
|
request = self.request_factory.get('/foo/')
|
|
|
|
middleware = SessionMiddleware(response_delete_session)
|
2016-01-08 16:08:08 +00:00
|
|
|
|
2016-10-25 11:23:14 +00: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.
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware(request)
|
2016-01-08 16:08:08 +00:00
|
|
|
|
2013-08-19 05:36:36 +00:00
|
|
|
def test_session_delete_on_end(self):
|
2019-09-26 17:06:35 +00:00
|
|
|
def response_ending_session(request):
|
|
|
|
request.session.flush()
|
|
|
|
return HttpResponse('Session test')
|
|
|
|
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(response_ending_session)
|
2013-08-19 05:36:36 +00:00
|
|
|
|
|
|
|
# Before deleting, there has to be an existing cookie
|
|
|
|
request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
2019-09-26 17:06:35 +00:00
|
|
|
response = middleware(request)
|
2013-08-19 05:36:36 +00:00
|
|
|
|
2016-10-27 07:53:39 +00:00
|
|
|
# The cookie was deleted, not recreated.
|
2013-08-19 05:36:36 +00:00
|
|
|
# A deleted cookie header looks like:
|
2017-12-27 21:49:46 +00:00
|
|
|
# Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
|
2014-09-04 12:15:09 +00:00
|
|
|
self.assertEqual(
|
2017-12-27 21:49:46 +00:00
|
|
|
'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
|
2020-07-16 06:16:58 +00:00
|
|
|
'Max-Age=0; Path=/; SameSite={}'.format(
|
2015-03-30 16:29:56 +00:00
|
|
|
settings.SESSION_COOKIE_NAME,
|
2020-07-16 06:16:58 +00:00
|
|
|
settings.SESSION_COOKIE_SAMESITE,
|
2015-03-30 16:29:56 +00:00
|
|
|
),
|
2014-09-04 12:15:09 +00:00
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
2019-03-18 15:15:06 +00:00
|
|
|
# SessionMiddleware sets 'Vary: Cookie' to prevent the 'Set-Cookie'
|
|
|
|
# from being cached.
|
|
|
|
self.assertEqual(response['Vary'], 'Cookie')
|
2013-08-19 05:36:36 +00:00
|
|
|
|
2016-06-21 15:03:25 +00:00
|
|
|
@override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/')
|
|
|
|
def test_session_delete_on_end_with_custom_domain_and_path(self):
|
2019-09-26 17:06:35 +00:00
|
|
|
def response_ending_session(request):
|
|
|
|
request.session.flush()
|
|
|
|
return HttpResponse('Session test')
|
|
|
|
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(response_ending_session)
|
2015-05-14 06:22:42 +00:00
|
|
|
|
|
|
|
# Before deleting, there has to be an existing cookie
|
|
|
|
request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'
|
|
|
|
|
|
|
|
# Handle the response through the middleware
|
2019-09-26 17:06:35 +00:00
|
|
|
response = middleware(request)
|
2015-05-14 06:22:42 +00:00
|
|
|
|
2016-10-27 07:53:39 +00:00
|
|
|
# The cookie was deleted, not recreated.
|
2016-06-21 15:03:25 +00:00
|
|
|
# A deleted cookie header with a custom domain and path looks like:
|
2015-05-14 06:22:42 +00:00
|
|
|
# Set-Cookie: sessionid=; Domain=.example.local;
|
2017-12-27 21:49:46 +00:00
|
|
|
# expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
|
2016-06-21 15:03:25 +00:00
|
|
|
# Path=/example/
|
2015-05-14 06:22:42 +00:00
|
|
|
self.assertEqual(
|
2017-02-18 00:45:34 +00:00
|
|
|
'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
|
2020-07-16 06:16:58 +00:00
|
|
|
'01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/; SameSite={}'.format(
|
2015-05-14 06:22:42 +00:00
|
|
|
settings.SESSION_COOKIE_NAME,
|
2020-07-16 06:16:58 +00:00
|
|
|
settings.SESSION_COOKIE_SAMESITE,
|
2015-05-14 06:22:42 +00:00
|
|
|
),
|
|
|
|
str(response.cookies[settings.SESSION_COOKIE_NAME])
|
|
|
|
)
|
|
|
|
|
2015-08-05 20:51:42 +00:00
|
|
|
def test_flush_empty_without_session_cookie_doesnt_set_cookie(self):
|
2019-09-26 17:06:35 +00:00
|
|
|
def response_ending_session(request):
|
|
|
|
request.session.flush()
|
|
|
|
return HttpResponse('Session test')
|
2015-08-05 20:51:42 +00:00
|
|
|
|
2019-09-26 17:06:35 +00:00
|
|
|
request = self.request_factory.get('/')
|
|
|
|
middleware = SessionMiddleware(response_ending_session)
|
2015-08-05 20:51:42 +00:00
|
|
|
|
|
|
|
# Handle the response through the middleware
|
2019-09-26 17:06:35 +00:00
|
|
|
response = middleware(request)
|
2015-08-05 20:51:42 +00:00
|
|
|
|
|
|
|
# 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-18 21:57:01 +00:00
|
|
|
def test_empty_session_saved(self):
|
2015-10-20 09:30:43 +00:00
|
|
|
"""
|
2015-08-18 21:57:01 +00:00
|
|
|
If a session is emptied of data but still has a key, it should still
|
|
|
|
be updated.
|
|
|
|
"""
|
2019-09-26 17:06:35 +00:00
|
|
|
def response_set_session(request):
|
|
|
|
# Set a session key and some data.
|
|
|
|
request.session['foo'] = 'bar'
|
|
|
|
return HttpResponse('Session test')
|
|
|
|
|
2018-11-26 19:01:27 +00:00
|
|
|
request = self.request_factory.get('/')
|
2019-09-26 17:06:35 +00:00
|
|
|
middleware = SessionMiddleware(response_set_session)
|
2015-08-18 21:57:01 +00:00
|
|
|
|
|
|
|
# Handle the response through the middleware.
|
2019-09-26 17:06:35 +00:00
|
|
|
response = middleware(request)
|
2015-08-18 21:57:01 +00:00
|
|
|
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 05:31:11 +00:00
|
|
|
|
2020-08-07 19:42:39 +00:00
|
|
|
class CookieSessionTests(SessionTestsMixin, SimpleTestCase):
|
2011-06-26 17:00:24 +00: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-17 17:37:24 +00:00
|
|
|
testing for this behavior is meaningless.
|
2011-06-26 17:00:24 +00:00
|
|
|
"""
|
|
|
|
pass
|
2012-10-28 15:51:51 +00:00
|
|
|
|
|
|
|
@unittest.expectedFailure
|
|
|
|
def test_actual_expiry(self):
|
|
|
|
# The cookie backend doesn't handle non-default expiry dates, see #19201
|
2017-01-21 13:13:44 +00:00
|
|
|
super().test_actual_expiry()
|
2015-03-11 17:46:39 +00: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 01:04:03 +00: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-08 16:08:08 +00: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
|