diff --git a/keystone/middleware/core.py b/keystone/middleware/core.py index 0f6c1e6333..aa02c62b24 100644 --- a/keystone/middleware/core.py +++ b/keystone/middleware/core.py @@ -98,21 +98,25 @@ class JsonBodyMiddleware(wsgi.Middleware): """ def process_request(self, request): - # Ignore unrecognized content types. Empty string indicates - # the client did not explicitly set the header - if not request.content_type in ('application/json', ''): - return - + # Abort early if we don't have any work to do params_json = request.body if not params_json: return + # Reject unrecognized content types. Empty string indicates + # the client did not explicitly set the header + if not request.content_type in ('application/json', ''): + e = exception.ValidationError(attribute='application/json', + target='Content-Type header') + return wsgi.render_exception(e) + params_parsed = {} try: params_parsed = json.loads(params_json) except ValueError: - msg = 'Malformed json in request body' - raise webob.exc.HTTPBadRequest(explanation=msg) + e = exception.ValidationError(attribute='valid JSON', + target='request body') + return wsgi.render_exception(e) finally: if not params_parsed: params_parsed = {} diff --git a/tests/test_middleware.py b/tests/test_middleware.py index a5740acd56..fca3977565 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -90,9 +90,8 @@ class JsonBodyMiddlewareTest(test.TestCase): req = make_request(body='{"arg1": "on', content_type='application/json', method='POST') - _middleware = middleware.JsonBodyMiddleware(None) - self.assertRaises(webob.exc.HTTPBadRequest, - _middleware.process_request, req) + resp = middleware.JsonBodyMiddleware(None).process_request(req) + self.assertEqual(resp.status_int, 400) def test_no_content_type(self): req = make_request(body='{"arg1": "one", "arg2": ["a"]}', @@ -105,6 +104,12 @@ class JsonBodyMiddlewareTest(test.TestCase): req = make_request(body='{"arg1": "one", "arg2": ["a"]}', content_type='text/plain', method='POST') + resp = middleware.JsonBodyMiddleware(None).process_request(req) + self.assertEqual(resp.status_int, 400) + + def test_unrecognized_content_type_without_body(self): + req = make_request(content_type='text/plain', + method='GET') middleware.JsonBodyMiddleware(None).process_request(req) params = req.environ.get(middleware.PARAMS_ENV, {}) self.assertEqual(params, {})