Commit 655eff96 authored by Karel Hanák's avatar Karel Hanák
Browse files

mqtt client: fixed request validation for invalid requests

parent 2f4db75a
Pipeline #4619 failed with stages
in 16 seconds
......@@ -88,15 +88,28 @@ class CMqtt(mqtt.Client):
"""
self.logger.info(request)
if request.payload:
schema_errors = sorted(self.validator.iter_errors(request.payload), key=str)
try:
payload = json.loads(request.payload.decode('utf-8'))
except json.JSONDecodeError as json_error:
self.logger.error(json_error.msg + ' at line ' + str(json_error.lineno) +
', column ' + str(json_error.colno) + ' on\n' + json_error.doc)
self.last_topic = request.topic.replace('requests', 'responses')
self.publish(self.last_topic, 'Invalid request format: ' +
json_error.msg + ' at line ' + str(json_error.lineno) +
', column ' + str(json_error.colno) + ' on\n' + json_error.doc, 0, False)
return TrRet.JSONErr
schema_errors = sorted(self.validator.iter_errors(payload), key=str)
if schema_errors:
errorString = ''
for error in schema_errors:
self.logger.error(error)
errorString += error.message
return TrRet.SchemaErr, errorString
self.last_topic = request.topic.replace('requests', 'responses')
self.publish(self.last_topic, errorString, 0, False)
return TrRet.SchemaErr
return TrRet.OK, None
return TrRet.OK
def on_connect(self, client, userdata, flags, rc): # pylint: disable=W0221 W0236 W0613
"""
......@@ -125,11 +138,7 @@ class CMqtt(mqtt.Client):
"""
self.logger.info('MQTT broker published on ' + msg.topic + ':\n' + msg.payload.decode('utf-8'))
pub_topic = msg.topic.replace("requests", "responses")
self.last_topic = pub_topic
ret, errors = self._validate_request(msg)
if ret == TrRet.OK:
if self._validate_request(msg) == TrRet.OK:
topic_tokens = msg.topic.split('/')
method = topic_tokens[4]
path = ''
......@@ -138,6 +147,8 @@ class CMqtt(mqtt.Client):
path += '/' + topic_tokens[i]
payload = msg.payload.decode('utf-8')
pub_topic = msg.topic.replace("requests", "responses")
self.last_topic = pub_topic
try:
if method == 'delete':
......@@ -154,8 +165,6 @@ class CMqtt(mqtt.Client):
self.logger.info(conn_err.strerror)
self.publish(self.last_topic, 'Could not establish connection with the REST API,'
' check logs for more details.', 0, False)
else:
self.publish(self.last_topic, errors, 0, False)
def on_publish(self, client, userdata, mid): # pylint: disable=W0221 W0236 W0613
"""
......
......@@ -6,7 +6,6 @@ from unittest.mock import Mock
from translator.cmqtt.mqtt_client import CMqtt
from translator.utils.tr_ret import TrRet
class TestCMqtt(unittest.TestCase):
def setUp(self):
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment