Merge pull request #1671 from jeffwidman/support-json-top-level-arrays
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add support for serializing top-level arrays to JSON
authored by David Lord · committed by David Lord · parents f17e606, daceb3e · Browse files · 5 files·+114 added−115 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+114 added−115 removed
- tests:+69 added−29 removed
- other:+45 added−86 removed
Provenance
- Commit
431db28- Tree
6dd9f0b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
f17e606- Parent 2
daceb3e
5 files changed+114 added−115 removed
modified:docs/security.rst+8 added-77 removed
93 unmodified lines94 95 JSON Security96 -------------97 98-.. admonition:: ECMAScript 5 Changes98+In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level99+arrays to JSON. This was because of a security vulnerability in ECMAScript 4.100 100- Starting with ECMAScript 5 the behavior of literals changed. Now they101- are not constructed with the constructor of ``Array`` and others, but102- with the builtin constructor of ``Array`` which closes this particular103- attack vector.104-105-JSON itself is a high-level serialization format, so there is barely106-anything that could cause security problems, right? You can't declare107-recursive structures that could cause problems and the only thing that108-could possibly break are very large responses that can cause some kind of109-denial of service at the receiver's side.110-111-However there is a catch. Due to how browsers work the CSRF issue comes112-up with JSON unfortunately. Fortunately there is also a weird part of the113-JavaScript specification that can be used to solve that problem easily and114-Flask is kinda doing that for you by preventing you from doing dangerous115-stuff. Unfortunately that protection is only there for116-:func:`~flask.jsonify` so you are still at risk when using other ways to117-generate JSON.118-119-So what is the issue and how to avoid it? The problem are arrays at120-top-level in JSON. Imagine you send the following data out in a JSON121-request. Say that's exporting the names and email addresses of all your122-friends for a part of the user interface that is written in JavaScript.123-Not very uncommon:124-125-.. sourcecode:: javascript126-127- [128- {"username": "admin",129- "email": "admin@localhost"}130- ]131-132-And it is doing that of course only as long as you are logged in and only133-for you. And it is doing that for all ``GET`` requests to a certain URL,134-say the URL for that request is135-``http://example.com/api/get_friends.json``.136-137-So now what happens if a clever hacker is embedding this to his website138-and social engineers a victim to visiting his site:139-140-.. sourcecode:: html141-142- <script type=text/javascript>143- var captured = [];144- var oldArray = Array;145- function Array() {146- var obj = this, id = 0, capture = function(value) {147- obj.__defineSetter__(id++, capture);148- if (value)149- captured.push(value);150- };151- capture();152- }153- </script>154- <script type=text/javascript155- src=http://example.com/api/get_friends.json></script>156- <script type=text/javascript>157- Array = oldArray;158- // now we have all the data in the captured array.159- </script>160-161-If you know a bit of JavaScript internals you might know that it's162-possible to patch constructors and register callbacks for setters. An163-attacker can use this (like above) to get all the data you exported in164-your JSON file. The browser will totally ignore the :mimetype:`application/json`165-mimetype if :mimetype:`text/javascript` is defined as content type in the script166-tag and evaluate that as JavaScript. Because top-level array elements are167-allowed (albeit useless) and we hooked in our own constructor, after that168-page loaded the data from the JSON response is in the `captured` array.169-170-Because it is a syntax error in JavaScript to have an object literal171-(``{...}``) toplevel an attacker could not just do a request to an172-external URL with the script tag to load up the data. So what Flask does173-is to only allow objects as toplevel elements when using174-:func:`~flask.jsonify`. Make sure to do the same when using an ordinary175-JSON generate function.101+ECMAScript 5 closed this vulnerability, so only extremely old browsers are102+still vulnerable. All of these browsers have `other more serious103+vulnerabilities104+<https://github.com/mitsuhiko/flask/issues/248#issuecomment-59934857>`_, so105+this behavior was changed and :func:`~flask.jsonify` now supports serializing106+arrays.modified:flask/json.py+32 added-8 removed
197 unmodified lines198 fp.write(unicode(htmlsafe_dumps(obj, **kwargs)))199 200 201 def jsonify(*args, **kwargs):202- """Creates a :class:`~flask.Response` with the JSON representation of203- the given arguments with an :mimetype:`application/json` mimetype. The204- arguments to this function are the same as to the :class:`dict`205- constructor.202+ """This function wraps :func:`dumps` to add a few enhancements that make203+ life easier. It turns the JSON output into a :class:`~flask.Response`204+ object with the :mimetype:`application/json` mimetype. For convenience, it205+ also converts multiple arguments into an array or multiple keyword arguments206+ into a dict. This means that both ``jsonify(1,2,3)`` and207+ ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.208 209+ For clarity, the JSON serialization behavior has the following differences210+ from :func:`dumps`:211+212+ 1. Single argument: Passed straight through to :func:`dumps`.213+ 2. Multiple arguments: Converted to an array before being passed to214+ :func:`dumps`.215+ 3. Multiple keyword arguments: Converted to a dict before being passed to216+ :func:`dumps`.217+ 4. Both args and kwargs: Behavior undefined and will throw an exception.218+219 Example usage::220 221 from flask import jsonify222 10 unmodified lines233 "email": "admin@localhost",234 "id": 42235 }236 225- For security reasons only objects are supported toplevel. For more226- information about this, have a look at :ref:`json-security`.237 238+ .. versionchanged:: 1.0239+ Added support for serializing top-level arrays. This introduces a240+ security risk in ancient browsers. See :ref:`json_security` for details.241+242 This function's response will be pretty printed if it was not requested243 with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless244 the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.245 Compressed (not pretty) formatting currently means no indents and no9 unmodified lines255 and not request.is_xhr:256 indent = 2257 separators = (', ', ': ')258 259+ if args and kwargs:260+ raise TypeError(261+ "jsonify() behavior undefined when passed both args and kwargs"262+ )263+ elif len(args) == 1: # single args are passed directly to dumps()264+ data = args[0]265+ elif args: # convert multiple args into an array266+ data = list(args)267+ else: # convert kwargs to a dict268+ data = dict(kwargs)269+270 # Note that we add '\n' to end of response271 # (see https://github.com/mitsuhiko/flask/pull/1262)272 rv = current_app.response_class(248- (dumps(dict(*args, **kwargs), indent=indent, separators=separators),249- '\n'),273+ (dumps(data, indent=indent, separators=separators), '\n'),274 mimetype='application/json')275 return rv276 277 2 unmodified linesmodified:tests/test_helpers.py+69 added-29 removed
29 unmodified lines30 31 32 class TestJSON(object):33 34- def test_jsonify_date_types(self):35- """Test jsonify with datetime.date and datetime.datetime types."""36-37- test_dates = (38- datetime.datetime(1973, 3, 11, 6, 30, 45),39- datetime.date(1975, 1, 5)40- )41-42- app = flask.Flask(__name__)43- c = app.test_client()44-45- for i, d in enumerate(test_dates):46- url = '/datetest{0}'.format(i)47- app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))48- rv = c.get(url)49- assert rv.mimetype == 'application/json'50- assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())51-34 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):35 app = flask.Flask(__name__)36 app.config['DEBUG'] = True37 @app.route('/json', methods=['POST'])46 unmodified lines84 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),85 content_type='application/json; charset=iso-8859-15')86 assert resp.data == u'Hällo Wörld'.encode('utf-8')87 106- def test_jsonify(self):107- d = dict(a=23, b=42, c=[1, 2, 3])88+ def test_json_as_unicode(self):89 app = flask.Flask(__name__)90+91+ app.config['JSON_AS_ASCII'] = True92+ with app.app_context():93+ rv = flask.json.dumps(u'\N{SNOWMAN}')94+ assert rv == '"\\u2603"'95+96+ app.config['JSON_AS_ASCII'] = False97+ with app.app_context():98+ rv = flask.json.dumps(u'\N{SNOWMAN}')99+ assert rv == u'"\u2603"'100+101+ def test_jsonify_basic_types(self):102+ """Test jsonify with basic types."""103+ # Should be able to use pytest parametrize on this, but I couldn't104+ # figure out the correct syntax105+ # https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions106+ test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)107+ app = flask.Flask(__name__)108+ c = app.test_client()109+ for i, d in enumerate(test_data):110+ url = '/jsonify_basic_types{0}'.format(i)111+ app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))112+ rv = c.get(url)113+ assert rv.mimetype == 'application/json'114+ assert flask.json.loads(rv.data) == d115+116+ def test_jsonify_dicts(self):117+ """Test jsonify with dicts and kwargs unpacking."""118+ d = dict(119+ a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,120+ h=['test list', 10, False],121+ i={'test':'dict'}122+ )123+ app = flask.Flask(__name__)124 @app.route('/kw')125 def return_kwargs():126 return flask.jsonify(**d)127 @app.route('/dict')4 unmodified lines132 rv = c.get(url)133 assert rv.mimetype == 'application/json'134 assert flask.json.loads(rv.data) == d135 121- def test_json_as_unicode(self):136+ def test_jsonify_arrays(self):137+ """Test jsonify of lists and args unpacking."""138+ l = [139+ 0, 42, 3.14, 't', 'hello', True, False,140+ ['test list', 2, False],141+ {'test':'dict'}142+ ]143 app = flask.Flask(__name__)144+ @app.route('/args_unpack')145+ def return_args_unpack():146+ return flask.jsonify(*l)147+ @app.route('/array')148+ def return_array():149+ return flask.jsonify(l)150+ c = app.test_client()151+ for url in '/args_unpack', '/array':152+ rv = c.get(url)153+ assert rv.mimetype == 'application/json'154+ assert flask.json.loads(rv.data) == l155 124- app.config['JSON_AS_ASCII'] = True125- with app.app_context():126- rv = flask.json.dumps(u'\N{SNOWMAN}')127- assert rv == '"\\u2603"'156+ def test_jsonify_date_types(self):157+ """Test jsonify with datetime.date and datetime.datetime types."""158 129- app.config['JSON_AS_ASCII'] = False130- with app.app_context():131- rv = flask.json.dumps(u'\N{SNOWMAN}')132- assert rv == u'"\u2603"'159+ test_dates = (160+ datetime.datetime(1973, 3, 11, 6, 30, 45),161+ datetime.date(1975, 1, 5)162+ )163 164+ app = flask.Flask(__name__)165+ c = app.test_client()166+167+ for i, d in enumerate(test_dates):168+ url = '/datetest{0}'.format(i)169+ app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))170+ rv = c.get(url)171+ assert rv.mimetype == 'application/json'172+ assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())173+174 def test_json_attr(self):175 app = flask.Flask(__name__)176 @app.route('/add', methods=['POST'])177 def add():543 unmodified linesmodified:AUTHORS+2 added-1 removed
13 unmodified lines14 - Chris Edgemon15 - Chris Grindstaff16 - Christopher Grebs17 - Daniel Neuhäuser18+- David Lord @davidism19 - Edmond Burnett20 - Florent Xicluna21 - Georg Brandl22+- Jeff Widman @jeffwidman23 - Justin Quick24 - Kenneth Reitz25 - Keyan Pishdadian26 - Marian Sigler6 unmodified lines33 - Simon Sapin34 - Stephane Wirtel35 - Thomas Schranz36 - Zhao Xiaohong35-- David Lord @davidismmodified:CHANGES+3 added
6 unmodified lines7 -----------8 9 (release date to be announced, codename to be selected)10 11+- Added support to serializing top-level arrays to :func:`flask.jsonify`. This12+ introduces a security risk in ancient browsers. See13+ :ref:`json_security` for details.14 - Added before_render_template signal.15 - Added `**kwargs` to :meth:`flask.Test.test_client` to support passing16 additional keyword arguments to the constructor of17 :attr:`flask.Flask.test_client_class`.542 unmodified lines