400 on unrecognized content type (bug 1012282)
Unrecognized content type: http://paste.openstack.org/raw/18537/ Malformed JSON: http://paste.openstack.org/raw/18536/ Change-Id: I76afbf9300bcb1c11bed74eddbe4972c451c5877
This commit is contained in:
parent
66a0b63dab
commit
489c6b60d1
@ -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 = {}
|
||||
|
@ -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, {})
|
||||
|
Loading…
Reference in New Issue
Block a user