From e9a18b4a2ac1b54c9079fae7f3efaebffdb60dd3 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 5 Dec 2023 20:02:56 +0000 Subject: [PATCH] Raise exception if invalid JSON numbers are encountered. --- django/http/parsers.py | 7 ++++++- tests/requests_tests/test_parsers.py | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/django/http/parsers.py b/django/http/parsers.py index 236cd318ab..d99a2b7d35 100644 --- a/django/http/parsers.py +++ b/django/http/parsers.py @@ -70,6 +70,11 @@ class JSONParser(BaseParser): def parse(self, request): from django.http import HttpRequest + def strict_constant(o): + raise ValueError( + "Out of range float values are not JSON compliant: " + repr(o) + ) + if isinstance(request, HttpRequest): request = request.body - return json.loads(request), MultiValueDict() + return json.loads(request, parse_constant=strict_constant), MultiValueDict() diff --git a/tests/requests_tests/test_parsers.py b/tests/requests_tests/test_parsers.py index c9ba5e001a..9769f3b614 100644 --- a/tests/requests_tests/test_parsers.py +++ b/tests/requests_tests/test_parsers.py @@ -60,3 +60,13 @@ class TestParsers(SimpleTestCase): msg = "You cannot change parsers after processing the request's content." with self.assertRaisesMessage(AttributeError, msg): request.parsers = [] + + def test_json_strict(self): + parser = JSONParser() + + msg_base = "Out of range float values are not JSON compliant: '%s'" + for value in ["Infinity", "-Infinity", "NaN"]: + with self.subTest(value=value): + msg = msg_base % value + with self.assertRaisesMessage(ValueError, msg): + parser.parse(bytes(value.encode()))