Merge branch 'json-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 · parents 22af78a, fe85970 · Browse files · 9 files·+163 added−53 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+163 added−53 removed
- other:+163 added−53 removed
Provenance
- Commit
e1a5761- Tree
4da9f54- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
22af78a- Parent 2
fe85970
9 files changed+163 added−53 removed
modified:docs/api.rst+3 added
213 unmodified lines214 215 .. autoclass:: SecureCookieSessionInterface216 :members:217 218+.. autoclass:: SecureCookieSession219+ :members:220+221 .. autoclass:: NullSession222 :members:223 224 .. autoclass:: SessionMixin442 unmodified linesmodified:docs/upgrading.rst+14 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.33+34+TODO: add external module for session upgrading35+36 Version 0.937 -----------38 39 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/__init__.py+3 added-3 removed
18 unmodified lines19 from jinja2 import Markup, escape20 21 from .app import Flask, Request, Response22 from .config import Config23-from .helpers import url_for, jsonify, json_available, flash, \23+from .helpers import url_for, jsonify, flash, \24 send_file, send_from_directory, get_flashed_messages, \25 get_template_attribute, make_response, safe_join, \26 stream_with_context27 from .globals import current_app, g, request, session, _request_ctx_stack, \8 unmodified lines36 from .signals import signals_available, template_rendered, request_started, \37 request_finished, got_request_exception, request_tearing_down38 39 # only import json if it's available40-if json_available:41- from .helpers import json40+from .helpers import json41 42 # backwards compat, goes away in 1.043 from .sessions import SecureCookieSession as Session44+json_available = Truemodified:flask/helpers.py+4 added-27 removed
21 unmodified lines22 from werkzeug.routing import BuildError23 from werkzeug.urls import url_quote24 from functools import update_wrapper25 26-# try to load the best simplejson implementation available. If JSON27-# is not installed, we add a failing class.28-json_available = True29-json = None30-try:31- import simplejson as json32-except ImportError:33- try:34- import json35- except ImportError:36- try:37- # Google Appengine offers simplejson via django38- from django.utils import simplejson as json39- except ImportError:40- json_available = False26+# Use the same json implementation as itsdangerous on which we27+# depend anyways.28+from itsdangerous import simplejson as json29 30 31 from werkzeug.datastructures import Headers32 from werkzeug.exceptions import NotFound9 unmodified lines42 from .globals import session, _request_ctx_stack, _app_ctx_stack, \43 current_app, request44 45 58-def _assert_have_json():59- """Helper function that fails if JSON is unavailable."""60- if not json_available:61- raise RuntimeError('simplejson not installed')62-63-46 # figure out if simplejson escapes slashes. This behavior was changed47 # from one version to another without reason.66-if not json_available or '\\/' not in json.dumps('/'):67-48+if '\\/' not in json.dumps('/'):49 def _tojson_filter(*args, **kwargs):69- if __debug__:70- _assert_have_json()50 return json.dumps(*args, **kwargs).replace('/', '\\/')51 else:52 _tojson_filter = json.dumps53 116 unmodified lines170 information about this, have a look at :ref:`json-security`.171 172 .. versionadded:: 0.2173 """195- if __debug__:196- _assert_have_json()174 return current_app.response_class(json.dumps(dict(*args, **kwargs),175 indent=None if request.is_xhr else 2), mimetype='application/json')176 177 695 unmodified linesmodified:flask/sessions.py+106 added-19 removed
8 unmodified lines9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+import hashlib14 from datetime import datetime14-from werkzeug.contrib.securecookie import SecureCookie15+from werkzeug.http import http_date, parse_date16+from werkzeug.datastructures import CallbackDict17+from .helpers import json18+from . import Markup19 20+from itsdangerous import URLSafeTimedSerializer, BadSignature21 22+23 class SessionMixin(object):24 """Expands a basic dictionary with an accessors that are expected25 by Flask extensions and users for the session.26 """19 unmodified lines46 #: The default mixin implementation just hardcodes `True` in.47 modified = True48 49 44-class SecureCookieSession(SecureCookie, SessionMixin):45- """Expands the session with support for switching between permanent46- and non-permanent sessions.50+class TaggedJSONSerializer(object):51+ """A customized JSON serializer that supports a few extra types that52+ we take for granted when serializing (tuples, markup objects, datetime).53 """54 55+ def dumps(self, value):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+ def object_hook(obj):72+ if len(obj) != 1:73+ return obj74+ the_key, the_value = obj.iteritems().next()75+ if the_key == ' t':76+ return tuple(the_value)77+ elif the_key == ' m':78+ return Markup(the_value)79+ elif the_key == ' d':80+ return parse_date(the_value)81+ return obj82+ return json.loads(value, object_hook=object_hook)83+84+85+session_json_serializer = TaggedJSONSerializer()86+87+88+class SecureCookieSession(CallbackDict, SessionMixin):89+ """Baseclass for sessions based on signed cookies."""90+91+ def __init__(self, initial=None):92+ def on_update(self):93+ self.modified = True94+ CallbackDict.__init__(self, initial, on_update)95+ self.modified = False96+97+98 class NullSession(SecureCookieSession):99 """Class used to generate nicer error messages if sessions are not100 available. Will still allow read-only access to the empty session101 but fail on setting.43 unmodified lines145 #: :meth:`is_null_session` method will perform a typecheck against146 #: this type.147 null_session_class = NullSession148 149+ #: A flag that indicates if the session interface is pickle based.150+ #: This can be used by flask extensions to make a decision in regards151+ #: to how to deal with the session object.152+ #:153+ #: .. versionadded:: 0.10154+ pickle_based = False155+156 def make_null_session(self, app):157 """Creates a null session which acts as a replacement object if the158 real session support could not be loaded due to a configuration159 error. This mainly aids the user experience because the job of the72 unmodified lines232 raise NotImplementedError()233 234 235 class SecureCookieSessionInterface(SessionInterface):181- """The cookie session interface that uses the Werkzeug securecookie182- as client side session backend.236+ """The default session interface that stores sessions in signed cookies237+ through the :mod:`itsdangerous` module.238 """239+ #: the salt that should be applied on top of the secret key for the240+ #: signing of cookie based sessions.241+ salt = 'cookie-session'242+ #: the hash function to use for the signature. The default is sha1243+ digest_method = staticmethod(hashlib.sha1)244+ #: the name of the itsdangerous supported key derivation. The default245+ #: is hmac.246+ key_derivation = 'hmac'247+ #: A python serializer for the payload. The default is a compact248+ #: JSON derived serializer with support for some extra Python types249+ #: such as datetime objects or tuples.250+ serializer = session_json_serializer251 session_class = SecureCookieSession252 253+ def get_signing_serializer(self, app):254+ if not app.secret_key:255+ return None256+ signer_kwargs = dict(257+ key_derivation=self.key_derivation,258+ digest_method=self.digest_method259+ )260+ return URLSafeTimedSerializer(app.secret_key, salt=self.salt,261+ serializer=self.serializer,262+ signer_kwargs=signer_kwargs)263+264 def open_session(self, app, request):187- key = app.secret_key188- if key is not None:189- return self.session_class.load_cookie(request,190- app.session_cookie_name,191- secret_key=key)265+ s = self.get_signing_serializer(app)266+ if s is None:267+ return None268+ val = request.cookies.get(app.session_cookie_name)269+ if not val:270+ return self.session_class()271+ max_age = app.permanent_session_lifetime.total_seconds()272+ try:273+ data = s.loads(val, max_age=max_age)274+ return self.session_class(data)275+ except BadSignature:276+ return self.session_class()277 278 def save_session(self, app, session, response):194- expires = self.get_expiration_time(app, session)279 domain = self.get_cookie_domain(app)280 path = self.get_cookie_path(app)281+ if not session:282+ if session.modified:283+ response.delete_cookie(app.session_cookie_name,284+ domain=domain, path=path)285+ return286 httponly = self.get_cookie_httponly(app)287 secure = self.get_cookie_secure(app)199- if session.modified and not session:200- response.delete_cookie(app.session_cookie_name, path=path,201- domain=domain)202- else:203- session.save_cookie(response, app.session_cookie_name, path=path,204- expires=expires, httponly=httponly,205- secure=secure, domain=domain)288+ expires = self.get_expiration_time(app, session)289+ val = self.get_signing_serializer(app).dumps(dict(session))290+ response.set_cookie(app.session_cookie_name, val,291+ expires=expires, httponly=httponly,292+ domain=domain, path=path, secure=secure)modified:flask/wrappers.py+1 added-3 removed
12 unmodified lines13 from werkzeug.utils import cached_property14 15 from .exceptions import JSONBadRequest16 from .debughelpers import attach_enctype_error_multidict17-from .helpers import json, _assert_have_json17+from .helpers import json18 from .globals import _request_ctx_stack19 20 21 class Request(RequestBase):72 unmodified lines94 parsed JSON data. Otherwise this will be `None`.95 96 This requires Python 2.6 or an installed version of simplejson.97 """98- if __debug__:99- _assert_have_json()98 if self.mimetype == 'application/json':99 request_charset = self.mimetype_params.get('charset')100 try:101 if request_charset is not None:45 unmodified linesmodified:CHANGES+4 added
6 unmodified lines7 ------------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 Campari.364 unmodified linesmodified:setup.py+2 added-1 removed
89 unmodified lines90 zip_safe=False,91 platforms='any',92 install_requires=[93 'Werkzeug>=0.7',94- 'Jinja2>=2.4'94+ 'Jinja2>=2.4',95+ 'itsdangerous>=0.17'96 ],97 classifiers=[98 'Development Status :: 4 - Beta',99 'Environment :: Web Environment',13 unmodified lines