Merge "400 on unrecognized content type (bug 1012282)"

This commit is contained in:
Jenkins 2012-06-19 19:28:33 +00:00 committed by Gerrit Code Review
commit bda35f25c7
2 changed files with 19 additions and 10 deletions

View File

@ -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 = {}

View File

@ -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, {})