Ensure JSON sent over websocket is a dictionary

The json lib in python can transform the input into many kinds of
data struct, such as int,str,boolean and so on. But only dict can
be handled by websocket. Now if the input is not dict like, the
zaqar-server will be stop at all. So before handle the request,
we should ensure the input format is acceptable.

Closes-bug: #1537965
Change-Id: I4e8bf4c0477741b40df3c58abb32ba73c792256c
This commit is contained in:
wangxiyuan 2016-01-21 19:29:35 +08:00
parent 24bce82b91
commit 865fcce6cc
2 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,47 @@
# Copyright 2016 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import mock
from zaqar.tests.unit.transport.websocket import base
class TestMessagingProtocol(base.TestBase):
config_file = "websocket_mongodb.conf"
def setUp(self):
super(TestMessagingProtocol, self).setUp()
self.protocol = self.transport.factory()
self.defaults = self.api.get_defaults()
def tearDown(self):
super(TestMessagingProtocol, self).tearDown()
def test_on_mesage_with_invalid_input(self):
payload = u'\ufeff'
send_mock = mock.Mock()
self.protocol.sendMessage = send_mock
self.protocol.onMessage(payload, False)
resp = json.loads(send_mock.call_args[0][0])
self.assertEqual(400, resp['headers']['status'])
payload = "123"
self.protocol.onMessage(payload, False)
resp = json.loads(send_mock.call_args[0][0])
self.assertEqual(400, resp['headers']['status'])

View File

@ -84,6 +84,12 @@ class MessagingProtocol(websocket.WebSocketServerProtocol):
body = {'error': str(ex)}
resp = self._handler.create_response(400, body)
return self._send_response(resp)
if not isinstance(payload, dict):
body = {
'error': "Unexpected body type. Expected dict or dict like"
}
resp = self._handler.create_response(400, body)
return self._send_response(resp)
req = self._handler.create_request(payload)
resp = self._handler.validate_request(payload, req)