Skip to content
Myr

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

5 files+172 added−1 removed

modified:docs/api.rst+7 added
213 unmodified lines
214215.. autoclass:: SecureCookieSessionInterface216 :members:217218.. autoclass:: UpgradeSecureCookieSessionInterface219220.. autoclass:: SecureCookieSession221 :members:222223.. autoclass:: UpgradeSecureCookieSession224225.. autoclass:: NullSession226 :members:227228.. autoclass:: SessionMixin
442 unmodified lines
modified:docs/upgrading.rst+51 added
17 unmodified lines
18installation, make sure to pass it the ``-U`` parameter::1920 $ easy_install -U Flask2122.. _upgrading-to-010:2324Version 0.1025------------2627The biggest change going from 0.9 to 0.10 is that the cookie serialization28format changed from pickle to a specialized JSON format. This change has29been done in order to avoid the damage an attacker can do if the secret30key is leaked. When you upgrade you will notice two major changes: all31sessions that were issued before the upgrade are invalidated and you can32only store a limited amount of types in the session. There are two ways33to avoid these problems on upgrading:3435Automatically Upgrade Sessions36``````````````````````````````3738The first method is to allow pickle based sessions for a limited amount of39time. This can be done by using the40:class:`~flask.sessions.UpgradeSecureCookieSession` session41implementation::4243 from flask import Flask44 from flask.sessions import UpgradeSecureCookieSessionInterface4546 app = Flask(__name__)47 app.session_interface = UpgradeSecureCookieSessionInterface4849For as long as this class is being used both pickle and json sessions are50supported but changes are written in JSON format only.5152Revert to Pickle Sessions53`````````````````````````5455You can also revert to pickle based sessions if you want::5657 import pickle58 from flask import Flask59 from flask.sessions import SecureCookieSession, \60 SecureCookieSessionInterface6162 class PickleSessionInterface(SecureCookieSessionInterface):63 class session_class(SecureCookieSession):64 serialization_method = pickle6566 app = Flask(__name__)67 app.session_interface = PickleSessionInterface6869If you want to continue to use pickle based data we strongly recommend70switching to a server side session store however.717273Version 0.974-----------7576The behavior of returning tuples from a function was simplified. If you
321 unmodified lines
modified:flask/testsuite/basic.py+26 added
11 unmodified lines
12from __future__ import with_statement1314import re15import flask16import pickle17import unittest18from datetime import datetime19from threading import Thread20from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning
276 unmodified lines
297 c = app.test_client()298 self.assert_equal(c.get('/').data, 'None')299 self.assert_equal(c.get('/').data, '42')300301 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)306307 @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 response313314 @app.route('/')315 def dump_session_contents():316 return pickle.dumps(dict(flask.session))317318 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))325326 def test_flashes(self):327 app = flask.Flask(__name__)328 app.secret_key = 'testkey'329
908 unmodified lines
modified:flask/sessions.py+79 added-1 removed
8 unmodified lines
9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import cPickle as pickle14from datetime import datetime15from werkzeug.contrib.securecookie import SecureCookie16from werkzeug.http import http_date, parse_date17from .helpers import json, _assert_have_json18from . import Markup192021class SessionMixin(object):22 """Expands a basic dictionary with an accessors that are expected
21 unmodified lines
44 #: The default mixin implementation just hardcodes `True` in.45 modified = True464748class 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 """5253 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=(',', ':'))6970 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)858687session_json_serializer = TaggedJSONSerializer()888990class 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_serializer969798class _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)106107108class 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.112113 .. versionadded:: 0.10114 """115 serialization_method = _UpgradeSerializer()116117118class 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 lines
270 else:271 session.save_cookie(response, app.session_cookie_name, path=path,272 expires=expires, httponly=httponly,273 secure=secure, domain=domain)274275276class 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.280281 .. versionadded:: 0.10282 """283 session_class = UpgradeSecureCookieSession
modified:CHANGES+9 added
1 unmodified line
2===============34Here you can see the full list of changes between each Flask release.56Version 0.107------------89Release date to be decided.1011- 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.1415Version 0.916-----------1718Released on July 1st 2012, codename Camapri.
364 unmodified lines