cfc0c9
From 50062c4d8c4108d17b7f12d9518ce883956d3921 Mon Sep 17 00:00:00 2001
cfc0c9
From: David Lord <davidism@gmail.com>
cfc0c9
Date: Tue, 10 Apr 2018 09:29:48 -0700
cfc0c9
Subject: [PATCH] detect UTF encodings when loading json
cfc0c9
cfc0c9
(cherry picked from commit 0e1e9a04aaf29ab78f721cfc79ac2a691f6e3929)
cfc0c9
---
cfc0c9
 flask/json.py         | 49 ++++++++++++++++++++++++++++++++++++++++++-
cfc0c9
 flask/wrappers.py     | 13 +++---------
cfc0c9
 tests/test_helpers.py | 28 ++++++++++++++-----------
cfc0c9
 3 files changed, 67 insertions(+), 23 deletions(-)
cfc0c9
cfc0c9
diff --git a/flask/json.py b/flask/json.py
cfc0c9
index 16e0c29..114873e 100644
cfc0c9
--- a/flask/json.py
cfc0c9
+++ b/flask/json.py
cfc0c9
@@ -8,6 +8,7 @@
cfc0c9
     :copyright: (c) 2015 by Armin Ronacher.
cfc0c9
     :license: BSD, see LICENSE for more details.
cfc0c9
 """
cfc0c9
+import codecs
cfc0c9
 import io
cfc0c9
 import uuid
cfc0c9
 from datetime import date
cfc0c9
@@ -108,6 +109,49 @@ def _load_arg_defaults(kwargs):
cfc0c9
         kwargs.setdefault('cls', JSONDecoder)
cfc0c9
 
cfc0c9
 
cfc0c9
+def detect_encoding(data):
cfc0c9
+    """Detect which UTF codec was used to encode the given bytes.
cfc0c9
+
cfc0c9
+    The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
cfc0c9
+    accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
cfc0c9
+    or little endian. Some editors or libraries may prepend a BOM.
cfc0c9
+
cfc0c9
+    :param data: Bytes in unknown UTF encoding.
cfc0c9
+    :return: UTF encoding name
cfc0c9
+    """
cfc0c9
+    head = data[:4]
cfc0c9
+
cfc0c9
+    if head[:3] == codecs.BOM_UTF8:
cfc0c9
+        return 'utf-8-sig'
cfc0c9
+
cfc0c9
+    if b'\x00' not in head:
cfc0c9
+        return 'utf-8'
cfc0c9
+
cfc0c9
+    if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):
cfc0c9
+        return 'utf-32'
cfc0c9
+
cfc0c9
+    if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):
cfc0c9
+        return 'utf-16'
cfc0c9
+
cfc0c9
+    if len(head) == 4:
cfc0c9
+        if head[:3] == b'\x00\x00\x00':
cfc0c9
+            return 'utf-32-be'
cfc0c9
+
cfc0c9
+        if head[::2] == b'\x00\x00':
cfc0c9
+            return 'utf-16-be'
cfc0c9
+
cfc0c9
+        if head[1:] == b'\x00\x00\x00':
cfc0c9
+            return 'utf-32-le'
cfc0c9
+
cfc0c9
+        if head[1::2] == b'\x00\x00':
cfc0c9
+            return 'utf-16-le'
cfc0c9
+
cfc0c9
+    if len(head) == 2:
cfc0c9
+        return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'
cfc0c9
+
cfc0c9
+    return 'utf-8'
cfc0c9
+
cfc0c9
+
cfc0c9
 def dumps(obj, **kwargs):
cfc0c9
     """Serialize ``obj`` to a JSON formatted ``str`` by using the application's
cfc0c9
     configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
cfc0c9
@@ -142,7 +186,10 @@ def loads(s, **kwargs):
cfc0c9
     """
cfc0c9
     _load_arg_defaults(kwargs)
cfc0c9
     if isinstance(s, bytes):
cfc0c9
-        s = s.decode(kwargs.pop('encoding', None) or 'utf-8')
cfc0c9
+        encoding = kwargs.pop('encoding', None)
cfc0c9
+        if encoding is None:
cfc0c9
+            encoding = detect_encoding(s)
cfc0c9
+        s = s.decode(encoding)
cfc0c9
     return _json.loads(s, **kwargs)
cfc0c9
 
cfc0c9
 
cfc0c9
diff --git a/flask/wrappers.py b/flask/wrappers.py
cfc0c9
index 04bdcb5..3e600fc 100644
cfc0c9
--- a/flask/wrappers.py
cfc0c9
+++ b/flask/wrappers.py
cfc0c9
@@ -144,17 +144,10 @@ class Request(RequestBase):
cfc0c9
         if not (force or self.is_json):
cfc0c9
             return None
cfc0c9
 
cfc0c9
-        # We accept a request charset against the specification as
cfc0c9
-        # certain clients have been using this in the past.  This
cfc0c9
-        # fits our general approach of being nice in what we accept
cfc0c9
-        # and strict in what we send out.
cfc0c9
-        request_charset = self.mimetype_params.get('charset')
cfc0c9
+        data = _get_data(self, cache)
cfc0c9
+
cfc0c9
         try:
cfc0c9
-            data = _get_data(self, cache)
cfc0c9
-            if request_charset is not None:
cfc0c9
-                rv = json.loads(data, encoding=request_charset)
cfc0c9
-            else:
cfc0c9
-                rv = json.loads(data)
cfc0c9
+            rv = json.loads(data)
cfc0c9
         except ValueError as e:
cfc0c9
             if silent:
cfc0c9
                 rv = None
cfc0c9
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
cfc0c9
index 9320ef7..9990782 100644
cfc0c9
--- a/tests/test_helpers.py
cfc0c9
+++ b/tests/test_helpers.py
cfc0c9
@@ -21,6 +21,8 @@ from werkzeug.datastructures import Range
cfc0c9
 from werkzeug.exceptions import BadRequest, NotFound
cfc0c9
 from werkzeug.http import parse_cache_control_header, parse_options_header
cfc0c9
 from werkzeug.http import http_date
cfc0c9
+
cfc0c9
+from flask import json
cfc0c9
 from flask._compat import StringIO, text_type
cfc0c9
 
cfc0c9
 
cfc0c9
@@ -34,6 +36,20 @@ def has_encoding(name):
cfc0c9
 
cfc0c9
 
cfc0c9
 class TestJSON(object):
cfc0c9
+    @pytest.mark.parametrize('value', (
cfc0c9
+        1, 't', True, False, None,
cfc0c9
+        [], [1, 2, 3],
cfc0c9
+        {}, {'foo': u'🐍'},
cfc0c9
+    ))
cfc0c9
+    @pytest.mark.parametrize('encoding', (
cfc0c9
+        'utf-8', 'utf-8-sig',
cfc0c9
+        'utf-16-le', 'utf-16-be', 'utf-16',
cfc0c9
+        'utf-32-le', 'utf-32-be', 'utf-32',
cfc0c9
+    ))
cfc0c9
+    def test_detect_encoding(self, value, encoding):
cfc0c9
+        data = json.dumps(value).encode(encoding)
cfc0c9
+        assert json.detect_encoding(data) == encoding
cfc0c9
+        assert json.loads(data) == value
cfc0c9
 
cfc0c9
     def test_ignore_cached_json(self):
cfc0c9
         app = flask.Flask(__name__)
cfc0c9
@@ -85,18 +101,6 @@ class TestJSON(object):
cfc0c9
         rv = c.post('/json', data='"foo"', content_type='application/x+json')
cfc0c9
         assert rv.data == b'foo'
cfc0c9
 
cfc0c9
-    def test_json_body_encoding(self):
cfc0c9
-        app = flask.Flask(__name__)
cfc0c9
-        app.testing = True
cfc0c9
-        @app.route('/')
cfc0c9
-        def index():
cfc0c9
-            return flask.request.get_json()
cfc0c9
-
cfc0c9
-        c = app.test_client()
cfc0c9
-        resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),
cfc0c9
-                     content_type='application/json; charset=iso-8859-15')
cfc0c9
-        assert resp.data == u'Hällo Wörld'.encode('utf-8')
cfc0c9
-
cfc0c9
     def test_json_as_unicode(self):
cfc0c9
         app = flask.Flask(__name__)
cfc0c9
 
cfc0c9
-- 
cfc0c9
2.17.1
cfc0c9