Skip to content
Myr

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

9 files+163 added−53 removed

modified:docs/api.rst+3 added
213 unmodified lines
214215.. autoclass:: SecureCookieSessionInterface216 :members:217218.. autoclass:: SecureCookieSession219 :members:220221.. autoclass:: NullSession222 :members:223224.. autoclass:: SessionMixin
442 unmodified lines
modified:docs/upgrading.rst+14 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.3334TODO: add external module for session upgrading3536Version 0.937-----------3839The 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/__init__.py+3 added-3 removed
18 unmodified lines
19from jinja2 import Markup, escape2021from .app import Flask, Request, Response22from .config import Config23from .helpers import url_for, jsonify, json_available, flash, \23from .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_context27from .globals import current_app, g, request, session, _request_ctx_stack, \
8 unmodified lines
36from .signals import signals_available, template_rendered, request_started, \37 request_finished, got_request_exception, request_tearing_down3839# only import json if it's available40if json_available:41 from .helpers import json40from .helpers import json4142# backwards compat, goes away in 1.043from .sessions import SecureCookieSession as Session44json_available = True
modified:flask/helpers.py+4 added-27 removed
21 unmodified lines
22from werkzeug.routing import BuildError23from werkzeug.urls import url_quote24from functools import update_wrapper2526# try to load the best simplejson implementation available. If JSON27# is not installed, we add a failing class.28json_available = True29json = None30try:31 import simplejson as json32except 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.28from itsdangerous import simplejson as json293031from werkzeug.datastructures import Headers32from werkzeug.exceptions import NotFound
9 unmodified lines
42from .globals import session, _request_ctx_stack, _app_ctx_stack, \43 current_app, request444558def _assert_have_json():59 """Helper function that fails if JSON is unavailable."""60 if not json_available:61 raise RuntimeError('simplejson not installed')626346# figure out if simplejson escapes slashes. This behavior was changed47# from one version to another without reason.66if not json_available or '\\/' not in json.dumps('/'):6748if '\\/' not in json.dumps('/'):49 def _tojson_filter(*args, **kwargs):69 if __debug__:70 _assert_have_json()50 return json.dumps(*args, **kwargs).replace('/', '\\/')51else:52 _tojson_filter = json.dumps53
116 unmodified lines
170 information about this, have a look at :ref:`json-security`.171172 .. 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')176177
695 unmodified lines
modified:flask/sessions.py+106 added-19 removed
8 unmodified lines
9 :copyright: (c) 2011 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import hashlib14from datetime import datetime14from werkzeug.contrib.securecookie import SecureCookie15from werkzeug.http import http_date, parse_date16from werkzeug.datastructures import CallbackDict17from .helpers import json18from . import Markup1920from itsdangerous import URLSafeTimedSerializer, BadSignature212223class SessionMixin(object):24 """Expands a basic dictionary with an accessors that are expected25 by Flask extensions and users for the session.26 """
19 unmodified lines
46 #: The default mixin implementation just hardcodes `True` in.47 modified = True484944class SecureCookieSession(SecureCookie, SessionMixin):45 """Expands the session with support for switching between permanent46 and non-permanent sessions.50class 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 """5455 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=(',', ':'))6970 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)838485session_json_serializer = TaggedJSONSerializer()868788class SecureCookieSession(CallbackDict, SessionMixin):89 """Baseclass for sessions based on signed cookies."""9091 def __init__(self, initial=None):92 def on_update(self):93 self.modified = True94 CallbackDict.__init__(self, initial, on_update)95 self.modified = False969798class 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 lines
145 #: :meth:`is_null_session` method will perform a typecheck against146 #: this type.147 null_session_class = NullSession148149 #: 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 = False155156 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 the
72 unmodified lines
232 raise NotImplementedError()233234235class 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 = SecureCookieSession252253 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)263264 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()277278 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 lines
13from werkzeug.utils import cached_property1415from .exceptions import JSONBadRequest16from .debughelpers import attach_enctype_error_multidict17from .helpers import json, _assert_have_json17from .helpers import json18from .globals import _request_ctx_stack192021class Request(RequestBase):
72 unmodified lines
94 parsed JSON data. Otherwise this will be `None`.9596 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 lines
modified:CHANGES+4 added
6 unmodified lines
7------------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 Campari.
364 unmodified lines
modified:setup.py+2 added-1 removed
89 unmodified lines
90 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