From 439a110993d044ab86d958294f5c78cfdd15465b Mon Sep 17 00:00:00 2001 From: Krzysztof Jagiello Date: Wed, 28 Aug 2019 13:27:22 +0200 Subject: [PATCH] Validate the request body when requesting nodes --- djedi/rest/api.py | 17 ++++++++++++++++- djedi/tests/test_rest.py | 27 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/djedi/rest/api.py b/djedi/rest/api.py index 56e41924..d90334ec 100644 --- a/djedi/rest/api.py +++ b/djedi/rest/api.py @@ -40,6 +40,21 @@ class NodesApi(APIView): """ @never_cache def post(self, request): + try: + json_body = json.loads(request.body) + except json.errors.JSONDecodeError: + return self.render_to_json( + {'error': 'Not a valid JSON body.'}, + status=400, + ) + if ( + not all(isinstance(k, six.string_types) for k in json_body.keys()) + or not all(isinstance(v, six.string_types) for v in json_body.values()) + ): + return self.render_to_json( + {'error': 'Invalid request body structure.'}, + status=400, + ) # Disable caching gets in CachePipe, defaults through this api is not trusted cio.conf.settings.configure( local=True, @@ -51,7 +66,7 @@ def post(self, request): ) nodes = [] - for uri, default in six.iteritems(json.loads(request.body)): + for uri, default in six.iteritems(json_body): node = cio.get(uri, default=default) nodes.append(node) diff --git a/djedi/tests/test_rest.py b/djedi/tests/test_rest.py index 404ff5ea..6388855d 100644 --- a/djedi/tests/test_rest.py +++ b/djedi/tests/test_rest.py @@ -312,3 +312,30 @@ def test_nodes(self): self.assertEqual(json_content['i18n://sv-se@rest/page/body.md'], u'

Foo Bar

') self.assertIn('i18n://sv-se@rest/label/email.txt#1', json_content.keys()) self.assertEqual(json_content['i18n://sv-se@rest/label/email.txt#1'], u'E-post') + + def test_nodes_invalid_body(self): + url = reverse('admin:djedi:rest:nodes') + + # Invalid JSON should be handled properly + response = self.client.post(url, '', content_type='application/json') + self.assertEqual(response.status_code, 400) + json_content = json.loads(response.content) + self.assertEqual( + json_content['error'], + 'Not a valid JSON body.', + ) + + # Invalid structure should be handled properly + response = self.client.post( + url, + json.dumps({ + 'rest/page/body.md': {'foo': 'bar'}, + }), + content_type='application/json', + ) + self.assertEqual(response.status_code, 400) + json_content = json.loads(response.content) + self.assertEqual( + json_content['error'], + 'Invalid request body structure.', + )