Implemented experimental JSON based sessions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent d4415dd · Browse files · 5 files·+172 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+172 added−1 removed
- other:+172 added−1 removed
Provenance
- Commit
4df3bf2- Tree
c1c21ee- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d4415dd
5 files changed+172 added−1 removed
modified:docs/api.rst+7 added
213 unmodified lines214 215 .. autoclass:: SecureCookieSessionInterface216 :members:217 218+.. autoclass:: UpgradeSecureCookieSessionInterface219+220+.. autoclass:: SecureCookieSession221+ :members:222+223+.. autoclass:: UpgradeSecureCookieSession224+225 .. autoclass:: NullSession226 :members:227 228 .. autoclass:: SessionMixin442 unmodified linesmodified:docs/upgrading.rst+51 added
17 unmodified lines18 installation, make sure to pass it the ``-U`` parameter::19 20 $ easy_install -U Flask21 22+.. _upgrading-to-010:23+24+Version 0.1025+------------26+27+The biggest change going from 0.9 to 0.10 is that the cookie serialization28+format changed from pickle to a specialized JSON format. This change has29+been done in order to avoid the damage an attacker can do if the secret30+key is leaked. When you upgrade you will notice two major changes: all31+sessions that were issued before the upgrade are invalidated and you can32+only store a limited amount of types in the session. There are two ways33+to avoid these problems on upgrading:34+35+Automatically Upgrade Sessions36+``````````````````````````````37+38+The first method is to allow pickle based sessions for a limited amount of39+time. This can be done by using the40+:class:`~flask.sessions.UpgradeSecureCookieSession` session41+implementation::42+43+ from flask import Flask44+ from flask.sessions import UpgradeSecureCookieSessionInterface45+46+ app = Flask(__name__)47+ app.session_interface = UpgradeSecureCookieSessionInterface48+49+For as long as this class is being used both pickle and json sessions are50+supported but changes are written in JSON format only.51+52+Revert to Pickle Sessions53+`````````````````````````54+55+You can also revert to pickle based sessions if you want::56+57+ import pickle58+ from flask import Flask59+ from flask.sessions import SecureCookieSession, \60+ SecureCookieSessionInterface61+62+ class PickleSessionInterface(SecureCookieSessionInterface):63+ class session_class(SecureCookieSession):64+ serialization_method = pickle65+66+ app = Flask(__name__)67+ app.session_interface = PickleSessionInterface68+69+If you want to continue to use pickle based data we strongly recommend70+switching to a server side session store however.71+72+73 Version 0.974 -----------75 76 The behavior of returning tuples from a function was simplified. If you321 unmodified linesmodified:flask/testsuite/basic.py+26 added
11 unmodified lines12 from __future__ import with_statement13 14 import re15 import flask16+import pickle17 import unittest18 from datetime import datetime19 from threading import Thread20 from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning276 unmodified lines297 c = app.test_client()298 self.assert_equal(c.get('/').data, 'None')299 self.assert_equal(c.get('/').data, '42')300 301+ def test_session_special_types(self):302+ app = flask.Flask(__name__)303+ app.secret_key = 'development-key'304+ app.testing = True305+ now = datetime.utcnow().replace(microsecond=0)306+307+ @app.after_request308+ def modify_session(response):309+ flask.session['m'] = flask.Markup('Hello!')310+ flask.session['dt'] = now311+ flask.session['t'] = (1, 2, 3)312+ return response313+314+ @app.route('/')315+ def dump_session_contents():316+ return pickle.dumps(dict(flask.session))317+318+ c = app.test_client()319+ c.get('/')320+ rv = pickle.loads(c.get('/').data)321+ self.assert_equal(rv['m'], flask.Markup('Hello!'))322+ self.assert_equal(type(rv['m']), flask.Markup)323+ self.assert_equal(rv['dt'], now)324+ self.assert_equal(rv['t'], (1, 2, 3))325+326 def test_flashes(self):327 app = flask.Flask(__name__)328 app.secret_key = 'testkey'329 908 unmodified linesmodified:flask/sessions.py+79 added-1 removed
8 unmodified lines9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+import cPickle as pickle14 from datetime import datetime15 from werkzeug.contrib.securecookie import SecureCookie16+from werkzeug.http import http_date, parse_date17+from .helpers import json, _assert_have_json18+from . import Markup19 20 21 class SessionMixin(object):22 """Expands a basic dictionary with an accessors that are expected21 unmodified lines44 #: The default mixin implementation just hardcodes `True` in.45 modified = True46 47 48+class TaggedJSONSerializer(object):49+ """A customized JSON serializer that supports a few extra types that50+ we take for granted when serializing (tuples, markup objects, datetime).51+ """52+53+ def dumps(self, value):54+ if __debug__:55+ _assert_have_json()56+ def _tag(value):57+ if isinstance(value, tuple):58+ return {'##t': [_tag(x) for x in value]}59+ elif callable(getattr(value, '__html__', None)):60+ return {'##m': unicode(value.__html__())}61+ elif isinstance(value, list):62+ return [_tag(x) for x in value]63+ elif isinstance(value, datetime):64+ return {'##d': http_date(value)}65+ elif isinstance(value, dict):66+ return dict((k, _tag(v)) for k, v in value.iteritems())67+ return value68+ return json.dumps(_tag(value), separators=(',', ':'))69+70+ def loads(self, value):71+ if __debug__:72+ _assert_have_json()73+ def object_hook(obj):74+ if len(obj) != 1:75+ return obj76+ the_key, the_value = obj.iteritems().next()77+ if the_key == '##t':78+ return tuple(the_value)79+ elif the_key == '##m':80+ return Markup(the_value)81+ elif the_key == '##d':82+ return parse_date(the_value)83+ return obj84+ return json.loads(value, object_hook=object_hook)85+86+87+session_json_serializer = TaggedJSONSerializer()88+89+90 class SecureCookieSession(SecureCookie, SessionMixin):91 """Expands the session with support for switching between permanent46- and non-permanent sessions.92+ and non-permanent sessions and changes the default pickle based93+ serialization format to a tagged json one.94 """95+ serialization_method = session_json_serializer96 97 98+class _UpgradeSerializer(object):99+ def dumps(self, value):100+ return session_json_serializer.dumps(value)101+ def loads(self, value):102+ try:103+ return session_json_serializer.loads(value)104+ except Exception:105+ return pickle.loads(value)106+107+108+class UpgradeSecureCookieSession(SecureCookieSession):109+ """This cookie sesion implementation tries json first but will also110+ support pickle based session. This exists mainly to upgrade existing111+ pickle based users transparently to json.112+113+ .. versionadded:: 0.10114+ """115+ serialization_method = _UpgradeSerializer()116+117+118 class NullSession(SecureCookieSession):119 """Class used to generate nicer error messages if sessions are not120 available. Will still allow read-only access to the empty session121 but fail on setting.148 unmodified lines270 else:271 session.save_cookie(response, app.session_cookie_name, path=path,272 expires=expires, httponly=httponly,273 secure=secure, domain=domain)274+275+276+class UpgradeSecureCookieSessionInterface(SecureCookieSessionInterface):277+ """This session interface works exactly like the regular one but uses278+ the :class:`UpgradeSecureCookieSession` classes to upgrade from pickle279+ sessions to JSON sessions.280+281+ .. versionadded:: 0.10282+ """283+ session_class = UpgradeSecureCookieSessionmodified:CHANGES+9 added
1 unmodified line2 ===============3 4 Here you can see the full list of changes between each Flask release.5 6+Version 0.107+------------8+9+Release date to be decided.10+11+- Changed default cookie serialization format from pickle to JSON to12+ limit the impact an attacker can do if the secret key leaks. See13+ :ref:`upgrading-to-010` for more information.14+15 Version 0.916 -----------17 18 Released on July 1st 2012, codename Camapri.364 unmodified lines