From a0fb6fa2b69378b4d2e011d9ef29301036b59e1c Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Tue, 13 Jul 2021 10:58:08 -0400 Subject: [PATCH] Island: Return 400 from POST /api/island_mode on invalid JSON --- monkey/monkey_island/cc/resources/island_mode.py | 8 ++++++-- .../monkey_island/cc/resources/test_island_mode.py | 6 ++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/monkey/monkey_island/cc/resources/island_mode.py b/monkey/monkey_island/cc/resources/island_mode.py index b69b399c0..5a83fb46a 100644 --- a/monkey/monkey_island/cc/resources/island_mode.py +++ b/monkey/monkey_island/cc/resources/island_mode.py @@ -14,12 +14,16 @@ logger = logging.getLogger(__name__) class IslandMode(flask_restful.Resource): @jwt_required def post(self): - body = json.loads(request.data) - mode_str = body.get("mode") try: + body = json.loads(request.data) + mode_str = body.get("mode") + mode = IslandModeEnum(mode_str) set_mode(mode) + return make_response({}, 200) + except (AttributeError, json.decoder.JSONDecodeError): + return make_response({}, 400) except ValueError: return make_response({}, 422) except Exception: diff --git a/monkey/tests/unit_tests/monkey_island/cc/resources/test_island_mode.py b/monkey/tests/unit_tests/monkey_island/cc/resources/test_island_mode.py index 9bd4d8dd3..b8d6a84c2 100644 --- a/monkey/tests/unit_tests/monkey_island/cc/resources/test_island_mode.py +++ b/monkey/tests/unit_tests/monkey_island/cc/resources/test_island_mode.py @@ -27,6 +27,12 @@ def test_island_mode_post__invalid_mode(flask_client): assert resp.status_code == 422 +@pytest.mark.parametrize("invalid_json", ["42", "{test"]) +def test_island_mode_post__invalid_json(flask_client, invalid_json): + resp = flask_client.post("/api/island-mode", data="{test", follow_redirects=True) + assert resp.status_code == 400 + + def test_island_mode_post__internal_server_error(monkeypatch, flask_client): monkeypatch.setattr(island_mode_resource, "set_mode", lambda x: raise_(Exception()))