From dd53ad68fb299ec4e2ffc37ff30be8bc3ef88719 Mon Sep 17 00:00:00 2001 From: Sergi Delgado Segura Date: Tue, 24 Mar 2020 19:55:41 +0100 Subject: [PATCH] Fixes bug when dealing with empty JSON requests or empty appointment field When posting a request via requests.post the json field was dumped to json, but it shouldn't have been since requests deals with this internally. That meant that the requests made by the code didn't match proper JSON. In line with this, the API was only parsing this type POST requests correctly, making add_appointment to fail if a proper formatted JSON was passed. On top of that, empty appointments were not checked in the Inspector before trying to get data from them, making it crash if a JSON was posted to add_appointment not containing the `appointment` field. Unit tests for this should be added. --- cli/teos_cli.py | 2 +- teos/api.py | 3 +-- teos/inspector.py | 3 +++ test/teos/unit/test_api.py | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/cli/teos_cli.py b/cli/teos_cli.py index f33daa8..a4609d3 100644 --- a/cli/teos_cli.py +++ b/cli/teos_cli.py @@ -249,7 +249,7 @@ def post_appointment(data, teos_url): logger.info("Sending appointment to the Eye of Satoshi") try: - return requests.post(url=add_appointment_endpoint, json=json.dumps(data), timeout=5) + return requests.post(url=add_appointment_endpoint, json=data, timeout=5) except ConnectTimeout: logger.error("Can't connect to the Eye of Satoshi's API. Connection timeout") diff --git a/teos/api.py b/teos/api.py index 31f612c..6aecb10 100644 --- a/teos/api.py +++ b/teos/api.py @@ -1,5 +1,4 @@ import os -import json import logging from flask import Flask, request, abort, jsonify @@ -55,7 +54,7 @@ class API: if request.is_json: # Check content type once if properly defined - request_data = json.loads(request.get_json()) + request_data = request.get_json() appointment = self.inspector.inspect( request_data.get("appointment"), request_data.get("signature"), request_data.get("public_key") ) diff --git a/teos/inspector.py b/teos/inspector.py index ed288fc..60a83fc 100644 --- a/teos/inspector.py +++ b/teos/inspector.py @@ -54,6 +54,9 @@ class Inspector: Errors are defined in :mod:`Errors `. """ + if appointment_data is None: + return errors.APPOINTMENT_EMPTY_FIELD, "empty appointment received" + block_height = self.block_processor.get_block_count() if block_height is not None: diff --git a/test/teos/unit/test_api.py b/test/teos/unit/test_api.py index ea65b4f..6cbf15f 100644 --- a/test/teos/unit/test_api.py +++ b/test/teos/unit/test_api.py @@ -72,7 +72,7 @@ def new_appt_data(): def add_appointment(new_appt_data): - r = requests.post(url=add_appointment_endpoint, json=json.dumps(new_appt_data), timeout=5) + r = requests.post(url=add_appointment_endpoint, json=new_appt_data, timeout=5) if r.status_code == 200: appointments.append(new_appt_data["appointment"])