From 5dffe7e0889dd76885d313c1d44a4b389f4b8667 Mon Sep 17 00:00:00 2001 From: "ahmed.helmy" Date: Thu, 5 Apr 2018 15:41:37 +0200 Subject: continue integrating validation Change-Id: Ifbda169affd649f9125581ac5b688b509d1f0d82 Signed-off-by: ahmed.helmy --- moon_manager/moon_manager/api/assignments.py | 10 + moon_manager/moon_manager/api/data.py | 10 + moon_manager/moon_manager/api/meta_data.py | 10 + moon_manager/moon_manager/api/meta_rules.py | 5 + moon_manager/moon_manager/api/models.py | 5 + moon_manager/moon_manager/api/pdp.py | 5 + moon_manager/moon_manager/api/perimeter.py | 14 ++ moon_manager/moon_manager/api/rules.py | 4 + .../unit_python/api/import_export_utilities.py | 12 +- .../tests/unit_python/api/meta_data_test.py | 42 ++++ .../tests/unit_python/api/meta_rules_test.py | 93 +++++++++ .../tests/unit_python/api/test_assignemnt.py | 75 ++++++- moon_manager/tests/unit_python/api/test_data.py | 64 ++++++ moon_manager/tests/unit_python/api/test_import.py | 4 +- moon_manager/tests/unit_python/api/test_pdp.py | 118 +++++++++++ .../tests/unit_python/api/test_perimeter.py | 231 ++++++++++++++------- moon_manager/tests/unit_python/api/test_rules.py | 58 +++++- .../tests/unit_python/api/test_unit_models.py | 94 +++++++++ .../python_moonutilities/security_functions.py | 111 +++++++++- .../tests/unit_python/test_validated_input.py | 191 +++++++++++++++++ 20 files changed, 1055 insertions(+), 101 deletions(-) create mode 100644 python_moonutilities/tests/unit_python/test_validated_input.py diff --git a/moon_manager/moon_manager/api/assignments.py b/moon_manager/moon_manager/api/assignments.py index 0b2cd20b..2ff9e218 100644 --- a/moon_manager/moon_manager/api/assignments.py +++ b/moon_manager/moon_manager/api/assignments.py @@ -12,6 +12,7 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import PolicyManager +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -31,6 +32,7 @@ class SubjectAssignments(Resource): "/policies//subject_assignments///", ) + @validate_input("get", kwargs_state=[True, False, False,False,False]) @check_auth def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -61,6 +63,7 @@ class SubjectAssignments(Resource): "error": str(e)}, 500 return {"subject_assignments": data} + @validate_input("post", kwargs_state=[True, False, False, False, False], body_state=[True, True, True]) @check_auth def post(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -100,6 +103,7 @@ class SubjectAssignments(Resource): "error": str(e)}, 500 return {"subject_assignments": data} + @validate_input("delete", kwargs_state=[True, True, True, True, False]) @check_auth def delete(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -141,6 +145,7 @@ class ObjectAssignments(Resource): "/policies//object_assignments///", ) + @validate_input("get", kwargs_state=[True, False, False,False,False]) @check_auth def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -171,6 +176,7 @@ class ObjectAssignments(Resource): "error": str(e)}, 500 return {"object_assignments": data} + @validate_input("post", kwargs_state=[True, False, False, False, False], body_state=[True, True, True]) @check_auth def post(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -210,6 +216,7 @@ class ObjectAssignments(Resource): "error": str(e)}, 500 return {"object_assignments": data} + @validate_input("delete", kwargs_state=[True, True, True, True, False]) @check_auth def delete(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -251,6 +258,7 @@ class ActionAssignments(Resource): "/policies//action_assignments///", ) + @validate_input("get", kwargs_state=[True, False, False,False,False]) @check_auth def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -281,6 +289,7 @@ class ActionAssignments(Resource): "error": str(e)}, 500 return {"action_assignments": data} + @validate_input("post", kwargs_state=[True, False, False, False, False], body_state=[True, True, True]) @check_auth def post(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): @@ -320,6 +329,7 @@ class ActionAssignments(Resource): "error": str(e)}, 500 return {"action_assignments": data} + @validate_input("delete", kwargs_state=[True, True, True, True, False]) @check_auth def delete(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): diff --git a/moon_manager/moon_manager/api/data.py b/moon_manager/moon_manager/api/data.py index 88c9d59a..2bf8d530 100644 --- a/moon_manager/moon_manager/api/data.py +++ b/moon_manager/moon_manager/api/data.py @@ -12,6 +12,7 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import PolicyManager +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -31,6 +32,7 @@ class SubjectData(Resource): "", ) + @validate_input("get", kwargs_state=[True, False, False, False]) @check_auth def get(self, uuid=None, category_id=None, data_id=None, user_id=None): """Retrieve all subject categories or a specific one if sid is given @@ -63,6 +65,7 @@ class SubjectData(Resource): "error": str(e)}, 500 return {"subject_data": data} + @validate_input("post", kwargs_state=[True, True, False, False], body_state=[True, False]) @check_auth def post(self, uuid=None, category_id=None, data_id=None, user_id=None): """Create or update a subject. @@ -98,6 +101,7 @@ class SubjectData(Resource): "error": str(e)}, 500 return {"subject_data": data} + @validate_input("delete", kwargs_state=[True, False, False, False]) @check_auth def delete(self, uuid=None, category_id=None, data_id=None, user_id=None): """Delete a subject for a given policy @@ -136,6 +140,7 @@ class ObjectData(Resource): "", ) + @validate_input("get", kwargs_state=[True, False, False, False]) @check_auth def get(self, uuid=None, category_id=None, data_id=None, user_id=None): """Retrieve all object categories or a specific one if sid is given @@ -168,6 +173,7 @@ class ObjectData(Resource): "error": str(e)}, 500 return {"object_data": data} + @validate_input("post", kwargs_state=[True, True, False, False], body_state=[True, False]) @check_auth def post(self, uuid=None, category_id=None, data_id=None, user_id=None): """Create or update a object. @@ -203,6 +209,7 @@ class ObjectData(Resource): "error": str(e)}, 500 return {"object_data": data} + @validate_input("delete", kwargs_state=[True, False, False, False]) @check_auth def delete(self, uuid=None, category_id=None, data_id=None, user_id=None): """Delete a object for a given policy @@ -241,6 +248,7 @@ class ActionData(Resource): "", ) + @validate_input("get", kwargs_state=[True, False, False, False]) @check_auth def get(self, uuid=None, category_id=None, data_id=None, user_id=None): """Retrieve all action categories or a specific one if sid is given @@ -273,6 +281,7 @@ class ActionData(Resource): "error": str(e)}, 500 return {"action_data": data} + @validate_input("post", kwargs_state=[True, True, False, False], body_state=[True, False]) @check_auth def post(self, uuid=None, category_id=None, data_id=None, user_id=None): """Create or update a action. @@ -308,6 +317,7 @@ class ActionData(Resource): "error": str(e)}, 500 return {"action_data": data} + @validate_input("delete", kwargs_state=[True, False, False, False]) @check_auth def delete(self, uuid=None, category_id=None, data_id=None, user_id=None): """Delete a action for a given policy diff --git a/moon_manager/moon_manager/api/meta_data.py b/moon_manager/moon_manager/api/meta_data.py index 104f26be..ab5702e4 100644 --- a/moon_manager/moon_manager/api/meta_data.py +++ b/moon_manager/moon_manager/api/meta_data.py @@ -12,6 +12,7 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import ModelManager +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -29,6 +30,7 @@ class SubjectCategories(Resource): "/subject_categories/", ) + @validate_input("get",kwargs_state=[False,False]) @check_auth def get(self, category_id=None, user_id=None): """Retrieve all subject categories or a specific one @@ -52,6 +54,7 @@ class SubjectCategories(Resource): "error": str(e)}, 500 return {"subject_categories": data} + @validate_input("post",body_state=[True,False]) @check_auth def post(self, category_id=None, user_id=None): """Create or update a subject category. @@ -79,6 +82,7 @@ class SubjectCategories(Resource): "error": str(e)}, 500 return {"subject_categories": data} + @validate_input("delete",kwargs_state=[True,False]) @check_auth def delete(self, category_id=None, user_id=None): """Delete a subject category @@ -112,6 +116,7 @@ class ObjectCategories(Resource): "/object_categories/", ) + @validate_input("get",kwargs_state=[False,False]) @check_auth def get(self, category_id=None, user_id=None): """Retrieve all object categories or a specific one @@ -135,6 +140,7 @@ class ObjectCategories(Resource): "error": str(e)}, 500 return {"object_categories": data} + @validate_input("post", body_state=[True, False]) @check_auth def post(self, category_id=None, user_id=None): """Create or update a object category. @@ -162,6 +168,7 @@ class ObjectCategories(Resource): "error": str(e)}, 500 return {"object_categories": data} + @validate_input("delete", kwargs_state=[True, False]) @check_auth def delete(self, category_id=None, user_id=None): """Delete an object category @@ -195,6 +202,7 @@ class ActionCategories(Resource): "/action_categories/", ) + @validate_input("get", kwargs_state=[False, False]) @check_auth def get(self, category_id=None, user_id=None): """Retrieve all action categories or a specific one @@ -218,6 +226,7 @@ class ActionCategories(Resource): "error": str(e)}, 500 return {"action_categories": data} + @validate_input("post", body_state=[True, False]) @check_auth def post(self, category_id=None, user_id=None): """Create or update an action category. @@ -245,6 +254,7 @@ class ActionCategories(Resource): "error": str(e)}, 500 return {"action_categories": data} + @validate_input("delete", kwargs_state=[True, False]) @check_auth def delete(self, category_id=None, user_id=None): """Delete an action diff --git a/moon_manager/moon_manager/api/meta_rules.py b/moon_manager/moon_manager/api/meta_rules.py index d2cbf5d1..7bec2ddf 100644 --- a/moon_manager/moon_manager/api/meta_rules.py +++ b/moon_manager/moon_manager/api/meta_rules.py @@ -12,6 +12,7 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import ModelManager +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -30,6 +31,7 @@ class MetaRules(Resource): "/meta_rules//" ) + @validate_input("get", kwargs_state=[False, False]) @check_auth def get(self, meta_rule_id=None, user_id=None): """Retrieve all sub meta rules @@ -58,6 +60,7 @@ class MetaRules(Resource): "error": str(e)}, 500 return {"meta_rules": data} + @validate_input("post", body_state=[True, True, True, True]) @check_auth def post(self, meta_rule_id=None, user_id=None): """Add a meta rule @@ -93,6 +96,7 @@ class MetaRules(Resource): "error": str(e)}, 500 return {"meta_rules": data} + @validate_input("patch", kwargs_state=[True, False], body_state=[True, True, True, True]) @check_auth def patch(self, meta_rule_id=None, user_id=None): """Update a meta rule @@ -128,6 +132,7 @@ class MetaRules(Resource): "error": str(e)}, 500 return {"meta_rules": data} + @validate_input("delete", kwargs_state=[True, False]) @check_auth def delete(self, meta_rule_id=None, user_id=None): """Delete a meta rule diff --git a/moon_manager/moon_manager/api/models.py b/moon_manager/moon_manager/api/models.py index 8a5f229c..37e96e47 100644 --- a/moon_manager/moon_manager/api/models.py +++ b/moon_manager/moon_manager/api/models.py @@ -11,6 +11,7 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import ModelManager +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -29,6 +30,7 @@ class Models(Resource): "/models//", ) + @validate_input("get", kwargs_state=[False, False]) @check_auth def get(self, uuid=None, user_id=None): """Retrieve all models @@ -52,6 +54,7 @@ class Models(Resource): "error": str(e)}, 500 return {"models": data} + @validate_input("post", body_state=[True, False, True]) @check_auth def post(self, uuid=None, user_id=None): """Create model. @@ -81,6 +84,7 @@ class Models(Resource): "error": str(e)}, 500 return {"models": data} + @validate_input("delete", kwargs_state=[True, False]) @check_auth def delete(self, uuid=None, user_id=None): """Delete a model @@ -101,6 +105,7 @@ class Models(Resource): "error": str(e)}, 500 return {"result": True} + @validate_input("patch", kwargs_state=[True, False], body_state=[True, False, True]) @check_auth def patch(self, uuid=None, user_id=None): """Update a model diff --git a/moon_manager/moon_manager/api/pdp.py b/moon_manager/moon_manager/api/pdp.py index 4bc34a24..5ffd2ab0 100644 --- a/moon_manager/moon_manager/api/pdp.py +++ b/moon_manager/moon_manager/api/pdp.py @@ -17,6 +17,7 @@ from python_moondb.core import PDPManager from python_moondb.core import PolicyManager from python_moondb.core import ModelManager from python_moonutilities import configuration, exceptions +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -96,6 +97,7 @@ class PDP(Resource): "/pdp//", ) + @validate_input("get", kwargs_state=[False, False]) @check_auth def get(self, uuid=None, user_id=None): """Retrieve all pdp @@ -120,6 +122,7 @@ class PDP(Resource): "error": str(e)}, 500 return {"pdps": data} + @validate_input("post", body_state=[True, True, True, False]) @check_auth def post(self, uuid=None, user_id=None): """Create pdp. @@ -161,6 +164,7 @@ class PDP(Resource): "error": str(e)}, 500 return {"pdps": data} + @validate_input("delete", kwargs_state=[True, False]) @check_auth def delete(self, uuid=None, user_id=None): """Delete a pdp @@ -182,6 +186,7 @@ class PDP(Resource): "error": str(e)}, 500 return {"result": True} + @validate_input("patch", kwargs_state=[True, False], body_state=[True, True, True, False]) @check_auth def patch(self, uuid=None, user_id=None): """Update a pdp diff --git a/moon_manager/moon_manager/api/perimeter.py b/moon_manager/moon_manager/api/perimeter.py index e1d999da..15f0dac3 100644 --- a/moon_manager/moon_manager/api/perimeter.py +++ b/moon_manager/moon_manager/api/perimeter.py @@ -15,6 +15,8 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import PolicyManager +from python_moonutilities.security_functions import validate_input + __version__ = "4.3.2" @@ -35,6 +37,7 @@ class Subjects(Resource): "/policies//subjects/", ) + @validate_input("get", kwargs_state=[False, False, False]) @check_auth def get(self, uuid=None, perimeter_id=None, user_id=None): """Retrieve all subjects or a specific one if perimeter_id is @@ -64,6 +67,7 @@ class Subjects(Resource): "error": str(e)}, 500 return {"subjects": data} + @validate_input("post", body_state=[True, False, False, False]) @check_auth def post(self, uuid=None, perimeter_id=None, user_id=None): """Create or update a subject. @@ -106,6 +110,7 @@ class Subjects(Resource): "error": str(e)}, 500 return {"subjects": data} + @validate_input("patch", kwargs_state=[False, True, False], body_state=[True, False, False, False]) @check_auth def patch(self, uuid=None, perimeter_id=None, user_id=None): """Create or update a subject. @@ -148,6 +153,7 @@ class Subjects(Resource): "error": str(e)}, 500 return {"subjects": data} + @validate_input("delete", kwargs_state=[False, True, False]) @check_auth def delete(self, uuid=None, perimeter_id=None, user_id=None): """Delete a subject for a given policy @@ -190,6 +196,7 @@ class Objects(Resource): "/policies//objects/", ) + @validate_input("get", kwargs_state=[False, False, False]) @check_auth def get(self, uuid=None, perimeter_id=None, user_id=None): """Retrieve all objects or a specific one if perimeter_id is @@ -218,6 +225,7 @@ class Objects(Resource): "error": str(e)}, 500 return {"objects": data} + @validate_input("post", body_state=[True, False, False, False]) @check_auth def post(self, uuid=None, perimeter_id=None, user_id=None): """Create or update a object. @@ -253,6 +261,7 @@ class Objects(Resource): "error": str(e)}, 500 return {"objects": data} + @validate_input("patch", kwargs_state=[False, True, False], body_state=[True, False, False, False]) @check_auth def patch(self, uuid=None, perimeter_id=None, user_id=None): """Create or update a object. @@ -288,6 +297,7 @@ class Objects(Resource): "error": str(e)}, 500 return {"objects": data} + @validate_input("delete", kwargs_state=[False, True, False]) @check_auth def delete(self, uuid=None, perimeter_id=None, user_id=None): """Delete a object for a given policy @@ -327,6 +337,7 @@ class Actions(Resource): "/policies//actions/", ) + @validate_input("get", kwargs_state=[False, False, False]) @check_auth def get(self, uuid=None, perimeter_id=None, user_id=None): """Retrieve all actions or a specific one if perimeter_id @@ -352,6 +363,7 @@ class Actions(Resource): "error": str(e)}, 500 return {"actions": data} + @validate_input("post", body_state=[True, False, False, False]) @check_auth def post(self, uuid=None, perimeter_id=None, user_id=None): """Create or update a action. @@ -387,6 +399,7 @@ class Actions(Resource): "error": str(e)}, 500 return {"actions": data} + @validate_input("patch", kwargs_state=[False, True, False], body_state=[True, False, False, False]) @check_auth def patch(self, uuid=None, perimeter_id=None, user_id=None): """Create or update a action. @@ -422,6 +435,7 @@ class Actions(Resource): "error": str(e)}, 500 return {"actions": data} + @validate_input("delete", kwargs_state=[False, True, False]) @check_auth def delete(self, uuid=None, perimeter_id=None, user_id=None): """Delete a action for a given policy diff --git a/moon_manager/moon_manager/api/rules.py b/moon_manager/moon_manager/api/rules.py index 57dcd45c..32c10030 100644 --- a/moon_manager/moon_manager/api/rules.py +++ b/moon_manager/moon_manager/api/rules.py @@ -11,6 +11,7 @@ from flask_restful import Resource import logging from python_moonutilities.security_functions import check_auth from python_moondb.core import PolicyManager +from python_moonutilities.security_functions import validate_input __version__ = "4.3.2" @@ -28,6 +29,7 @@ class Rules(Resource): "/policies//rules//", ) + @validate_input("get", kwargs_state=[False, False, False]) @check_auth def get(self, uuid=None, rule_id=None, user_id=None): """Retrieve all rules or a specific one @@ -57,6 +59,7 @@ class Rules(Resource): "error": str(e)}, 500 return {"rules": data} + @validate_input("post", kwargs_state=[True, False, False], body_state=[True, False, False, False]) @check_auth def post(self, uuid=None, rule_id=None, user_id=None): """Add a rule to a meta rule @@ -119,6 +122,7 @@ class Rules(Resource): "error": str(e)}, 500 return {"rules": data} + @validate_input("delete", kwargs_state=[True, True, False]) @check_auth def delete(self, uuid=None, rule_id=None, user_id=None): """Delete one rule linked to a specific sub meta rule diff --git a/moon_manager/tests/unit_python/api/import_export_utilities.py b/moon_manager/tests/unit_python/api/import_export_utilities.py index 3c921e21..b1c8a541 100644 --- a/moon_manager/tests/unit_python/api/import_export_utilities.py +++ b/moon_manager/tests/unit_python/api/import_export_utilities.py @@ -35,8 +35,8 @@ def clean_policies(client): def clean_subjects(client): subjects = test_perimeter.get_subjects(client) logger.info("subjects {}".format(subjects)) - for key in subjects["subjects"]: - subject = subjects["subjects"][key] + for key in subjects[1]["subjects"]: + subject = subjects[1]["subjects"][key] policy_keys = subject["policy_list"] logger.info("subjects policy_keys {}".format(policy_keys)) for policy_key in policy_keys: @@ -48,8 +48,8 @@ def clean_subjects(client): def clean_objects(client): objects = test_perimeter.get_objects(client) logger.info("objects {}".format(objects)) - for key in objects["objects"]: - object_ = objects["objects"][key] + for key in objects[1]["objects"]: + object_ = objects[1]["objects"][key] policy_keys = object_["policy_list"] logger.info("objects policy_keys {}".format(policy_keys)) for policy_key in policy_keys: @@ -62,8 +62,8 @@ def clean_objects(client): def clean_actions(client): actions = test_perimeter.get_actions(client) logger.info("objects {}".format(actions)) - for key in actions["actions"]: - action = actions["actions"][key] + for key in actions[1]["actions"]: + action = actions[1]["actions"][key] policy_keys = action["policy_list"] logger.info("action policy_keys {}".format(policy_keys)) for policy_key in policy_keys: diff --git a/moon_manager/tests/unit_python/api/meta_data_test.py b/moon_manager/tests/unit_python/api/meta_data_test.py index 0d67a8cd..8609f0b5 100644 --- a/moon_manager/tests/unit_python/api/meta_data_test.py +++ b/moon_manager/tests/unit_python/api/meta_data_test.py @@ -54,6 +54,20 @@ def test_add_subject_categories(): assert value['description'] == "description of {}".format("testuser") +def test_add_subject_categories_with_empty_user(): + client = utilities.register_client() + req, subject_categories = add_subject_categories(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_subject_categories_with_user_contain_space(): + client = utilities.register_client() + req, subject_categories = add_subject_categories(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + def test_delete_subject_categories(): client = utilities.register_client() req = delete_subject_categories(client, "testuser") @@ -119,6 +133,20 @@ def test_add_object_categories(): assert value['description'] == "description of {}".format("testuser") +def test_add_object_categories_with_empty_user(): + client = utilities.register_client() + req, object_categories = add_object_categories(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_object_categories_with_user_contain_space(): + client = utilities.register_client() + req, object_categories = add_object_categories(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + def test_delete_object_categories(): client = utilities.register_client() req = delete_object_categories(client, "testuser") @@ -184,6 +212,20 @@ def test_add_action_categories(): assert value['description'] == "description of {}".format("testuser") +def test_add_action_categories_with_empty_user(): + client = utilities.register_client() + req, action_categories = add_action_categories(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_action_categories_with_user_contain_space(): + client = utilities.register_client() + req, action_categories = add_action_categories(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + def test_delete_action_categories(): client = utilities.register_client() req = delete_action_categories(client, "testuser") diff --git a/moon_manager/tests/unit_python/api/meta_rules_test.py b/moon_manager/tests/unit_python/api/meta_rules_test.py index b5b1ecf8..a87c16f3 100644 --- a/moon_manager/tests/unit_python/api/meta_rules_test.py +++ b/moon_manager/tests/unit_python/api/meta_rules_test.py @@ -22,6 +22,46 @@ def add_meta_rules(client, name): return req, meta_rules +def add_meta_rules_without_subject_category_ids(client, name): + data = { + "name": name, + "subject_categories": [], + "object_categories": ["object_category_id1"], + "action_categories": ["action_category_id1"] + } + req = client.post("/meta_rules", data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + meta_rules = utilities.get_json(req.data) + return req, meta_rules + + +def update_meta_rules(client, name, metaRuleId): + data = { + "name": name, + "subject_categories": ["subject_category_id1_update", + "subject_category_id2_update"], + "object_categories": ["object_category_id1_update"], + "action_categories": ["action_category_id1_update"] + } + req = client.patch("/meta_rules/{}".format(metaRuleId), data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + meta_rules = utilities.get_json(req.data) + return req, meta_rules + + +def update_meta_rules_without_subject_category_ids(client, name): + data = { + "name": name, + "subject_categories": [], + "object_categories": ["object_category_id1"], + "action_categories": ["action_category_id1"] + } + req = client.post("/meta_rules", data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + meta_rules = utilities.get_json(req.data) + return req, meta_rules + + def delete_meta_rules(client, name): request, meta_rules = get_meta_rules(client) for key, value in meta_rules['meta_rules'].items(): @@ -57,6 +97,27 @@ def test_add_meta_rules(): assert value["action_categories"][0] == "action_category_id1" +def test_add_meta_rules_with_empty_user(): + client = utilities.register_client() + req, meta_rules = add_meta_rules(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_meta_rules_with_user_contain_space(): + client = utilities.register_client() + req, meta_rules = add_meta_rules(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_add_meta_rules_without_subject_categories(): + client = utilities.register_client() + req, meta_rules = add_meta_rules_without_subject_category_ids(client, "testuser") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty Container' + + def test_delete_meta_rules(): client = utilities.register_client() req = delete_meta_rules(client, "testuser") @@ -67,3 +128,35 @@ def test_delete_meta_rules_without_id(): client = utilities.register_client() req = delete_meta_rules_without_id(client) assert req.status_code == 500 + + +def test_update_meta_rules(): + client = utilities.register_client() + req = add_meta_rules(client, "testuser") + meta_rule_id = list(req[1]['meta_rules'])[0] + req_update = update_meta_rules(client, "testuser", meta_rule_id) + assert req_update[0].status_code == 200 + value = list(req_update[1]["meta_rules"].values())[0] + assert value["subject_categories"][0] == "subject_category_id1_update" + delete_meta_rules(client, "testuser") + get_meta_rules(client) + + +def test_update_meta_rules_without_id(): + client = utilities.register_client() + req_update = update_meta_rules(client, "testuser", "") + assert req_update[0].status_code == 500 + + +def test_update_meta_rules_without_user(): + client = utilities.register_client() + req_update = update_meta_rules(client, "", "") + assert req_update[0].status_code == 500 + assert json.loads(req_update[0].data)["message"] == "Empty String" + + +def test_update_meta_rules_without_subject_categories(): + client = utilities.register_client() + req_update = update_meta_rules_without_subject_category_ids(client, "testuser") + assert req_update[0].status_code == 500 + assert json.loads(req_update[0].data)["message"] == "Empty Container" diff --git a/moon_manager/tests/unit_python/api/test_assignemnt.py b/moon_manager/tests/unit_python/api/test_assignemnt.py index 9fd83857..4e2acddc 100644 --- a/moon_manager/tests/unit_python/api/test_assignemnt.py +++ b/moon_manager/tests/unit_python/api/test_assignemnt.py @@ -17,14 +17,14 @@ def add_subject_assignment(client, policy_id, category_id): "category_id": category_id, "data_id": "data_id1" } - req = client.post("/policies/{}/subject_assignments/{}".format(policy_id, category_id), data=json.dumps(data), + req = client.post("/policies/{}/subject_assignments".format(policy_id), data=json.dumps(data), headers={'Content-Type': 'application/json'}) subject_assignment = utilities.get_json(req.data) return req, subject_assignment -def delete_subject_assignment(client, policy_id): - req = client.delete("/policies/{}/subject_assignments".format(policy_id)) +def delete_subject_assignment(client, policy_id, sub_id, cat_id,data_id): + req = client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_id, sub_id, cat_id,data_id)) return req @@ -42,6 +42,14 @@ def test_add_subject_assignment(): assert value[id]['subject_id'] == "id1" +def test_add_subject_assignment_without_cat_id(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, subject_assignment = add_subject_assignment(client, policy_id, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty String' + + def test_get_subject_assignment(): policy_id = utilities.get_policy_id() client = utilities.register_client() @@ -54,9 +62,19 @@ def test_get_subject_assignment(): def test_delete_subject_assignment(): client = utilities.register_client() policy_id = utilities.get_policy_id() - success_req = delete_subject_assignment(client, policy_id) + req, subject_assignment = get_subject_assignment(client, policy_id) + value = subject_assignment["subject_assignments"] + id = list(value.keys())[0] + success_req = delete_subject_assignment(client, policy_id, value[id]['subject_id'], value[id]['category_id'],value[id]['assignments'][0]) assert success_req.status_code == 200 + +def test_delete_subject_assignment_without_policy_id(): + client = utilities.register_client() + success_req = delete_subject_assignment(client, "", "id1", "111" ,"data_id1") + assert success_req.status_code == 500 + + # --------------------------------------------------------------------------- # object_categories_test @@ -80,8 +98,8 @@ def add_object_assignment(client, policy_id, category_id): return req, object_assignment -def delete_object_assignment(client, policy_id): - req = client.delete("/policies/{}/object_assignments".format(policy_id)) +def delete_object_assignment(client, policy_id, obj_id, cat_id, data_id): + req = client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_id, obj_id, cat_id, data_id)) return req @@ -108,12 +126,30 @@ def test_add_object_assignment(): assert value[id]['object_id'] == "id1" +def test_add_object_assignment_without_cat_id(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, object_assignment = add_object_assignment(client, policy_id, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty String' + + def test_delete_object_assignment(): client = utilities.register_client() policy_id = utilities.get_policy_id() - success_req = delete_object_assignment(client, policy_id) + req, object_assignment = get_object_assignment(client, policy_id) + value = object_assignment["object_assignments"] + id = list(value.keys())[0] + success_req = delete_object_assignment(client, policy_id, value[id]['object_id'], value[id]['category_id'],value[id]['assignments'][0]) assert success_req.status_code == 200 + +def test_delete_object_assignment_without_policy_id(): + client = utilities.register_client() + success_req = delete_object_assignment(client, "", "id1", "111" ,"data_id1") + assert success_req.status_code == 500 + + # --------------------------------------------------------------------------- # action_categories_test @@ -137,8 +173,8 @@ def add_action_assignment(client, policy_id, category_id): return req, action_assignment -def delete_action_assignment(client, policy_id): - req = client.delete("/policies/{}/action_assignments".format(policy_id)) +def delete_action_assignment(client, policy_id, action_id, cat_id, data_id): + req = client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_id, action_id, cat_id, data_id)) return req @@ -165,10 +201,27 @@ def test_add_action_assignment(): assert value[id]['action_id'] == "id1" +def test_add_action_assignment_without_cat_id(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, action_assignment = add_action_assignment(client, policy_id, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty String' + + def test_delete_action_assignment(): client = utilities.register_client() policy_id = utilities.get_policy_id() - success_req = delete_action_assignment(client, policy_id) + req, action_assignment = get_action_assignment(client, policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_action_assignment(client, policy_id, value[id]['action_id'], value[id]['category_id'],value[id]['assignments'][0]) assert success_req.status_code == 200 -# --------------------------------------------------------------------------- \ No newline at end of file + +def test_delete_action_assignment_without_policy_id(): + client = utilities.register_client() + success_req = delete_action_assignment(client, "", "id1", "111" ,"data_id1") + assert success_req.status_code == 500 + +# --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_data.py b/moon_manager/tests/unit_python/api/test_data.py index 724f919f..f806ea2a 100644 --- a/moon_manager/tests/unit_python/api/test_data.py +++ b/moon_manager/tests/unit_python/api/test_data.py @@ -63,6 +63,28 @@ def test_delete_subject_data(): success_req = delete_subject_data(client, policy_id) assert success_req.status_code == 200 + +def test_add_subject_data_with_empty_user(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, subject_data = add_subject_data(client, "", policy_id, "111") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_subject_data_with_user_contain_space(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, subject_data = add_subject_data(client, "test user", policy_id, "111") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_delete_subject_data_without_policy_id(): + client = utilities.register_client() + success_req = delete_subject_data(client, "") + assert success_req.status_code == 500 + # --------------------------------------------------------------------------- # object_categories_test @@ -125,6 +147,27 @@ def test_delete_object_data(): success_req = delete_object_data(client, policy_id) assert success_req.status_code == 200 + +def test_add_object_data_with_empty_user(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, subject_data = add_subject_data(client, "", policy_id, "111") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_object_data_with_user_contain_space(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, object_data = add_object_data(client, "test user", policy_id, "111") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_delete_object_data_without_policy_id(): + client = utilities.register_client() + success_req = delete_object_data(client, "") + assert success_req.status_code == 500 # --------------------------------------------------------------------------- # action_categories_test @@ -183,4 +226,25 @@ def test_delete_action_data(): success_req = delete_action_data(client, policy_id) assert success_req.status_code == 200 + +def test_add_action_data_with_empty_user(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, action_data = add_action_data(client, "", policy_id, "111") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_action_data_with_user_contain_space(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, action_data = add_action_data(client, "test user", policy_id, "111") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_delete_action_data_without_policy_id(): + client = utilities.register_client() + success_req = delete_action_data(client, "") + assert success_req.status_code == 500 # --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_import.py b/moon_manager/tests/unit_python/api/test_import.py index 3c45f8a1..12a1cc6b 100644 --- a/moon_manager/tests/unit_python/api/test_import.py +++ b/moon_manager/tests/unit_python/api/test_import.py @@ -137,8 +137,6 @@ RULES = [{"rules": [{"meta_rule": {"name": "unknown meta rule"}, "policy": {"nam {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}] - - def test_import_models_without_new_meta_rules(): client = utilities.register_client() import_export_utilities.clean_all(client) @@ -240,7 +238,7 @@ def test_import_subject_object_action(): assert data == "Import ok !" get_elements = get_method(client) - get_elements = get_elements[type_element + "s"] + get_elements = get_elements[1][type_element + "s"] assert len(list(get_elements.keys())) == 1 values = list(get_elements.values()) diff --git a/moon_manager/tests/unit_python/api/test_pdp.py b/moon_manager/tests/unit_python/api/test_pdp.py index a2d0cb5a..fbaa6c7b 100644 --- a/moon_manager/tests/unit_python/api/test_pdp.py +++ b/moon_manager/tests/unit_python/api/test_pdp.py @@ -16,6 +16,13 @@ def add_pdp(client, data): return req, pdp +def update_pdp(client, data, pdp_id): + req = client.patch("/pdp/{}".format(pdp_id), data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + pdp = utilities.get_json(req.data) + return req, pdp + + def delete_pdp(client, key): req = client.delete("/pdp/{}".format(key)) return req @@ -60,3 +67,114 @@ def test_delete_pdp(): success_req = delete_pdp(client, key) break assert success_req.status_code == 200 + + +def test_add_pdp_with_empty_user(): + data = { + "name": "", + "security_pipeline": ["policy_id_1", "policy_id_2"], + "keystone_project_id": "keystone_project_id", + "description": "description of testuser" + } + client = utilities.register_client() + req, models = add_pdp(client, data) + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_pdp_with_user_contain_space(): + data = { + "name": "test user", + "security_pipeline": ["policy_id_1", "policy_id_2"], + "keystone_project_id": "keystone_project_id", + "description": "description of testuser" + } + client = utilities.register_client() + req, models = add_pdp(client, data) + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_add_pdp_without_security_pipeline(): + data = { + "name": "testuser", + "security_pipeline": [], + "keystone_project_id": "keystone_project_id", + "description": "description of testuser" + } + client = utilities.register_client() + req, meta_rules = add_pdp(client, data) + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty Container' + + +def test_add_pdp_without_keystone(): + data = { + "name": "testuser", + "security_pipeline": ["policy_id_1", "policy_id_2"], + "keystone_project_id": "", + "description": "description of testuser" + } + client = utilities.register_client() + req, meta_rules = add_pdp(client, data) + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty String' + + +def test_update_pdp(): + data_add = { + "name": "testuser", + "security_pipeline": ["policy_id_1", "policy_id_2"], + "keystone_project_id": "keystone_project_id", + "description": "description of testuser" + } + data_update = { + "name": "testuser", + "security_pipeline": ["policy_id_1_update", "policy_id_2_update"], + "keystone_project_id": "keystone_project_id_update", + "description": "description of testuser" + } + client = utilities.register_client() + req = add_pdp(client, data_add) + pdp_id = list(req[1]['pdps'])[0] + req_update = update_pdp(client, data_update, pdp_id) + assert req_update[0].status_code == 200 + value = list(req_update[1]["pdps"].values())[0] + assert value["keystone_project_id"] == "keystone_project_id_update" + request, pdp = get_pdp(client) + for key, value in pdp['pdps'].items(): + if value['name'] == "testuser": + delete_pdp(client, key) + break + + +def test_update_pdp_without_id(): + client = utilities.register_client() + req_update = update_pdp(client, "testuser", "") + assert req_update[0].status_code == 500 + + +def test_update_pdp_without_user(): + data = { + "name": "", + "security_pipeline": ["policy_id_1", "policy_id_2"], + "keystone_project_id": "keystone_project_id", + "description": "description of testuser" + } + client = utilities.register_client() + req_update = update_pdp(client, data, "") + assert req_update[0].status_code == 500 + assert json.loads(req_update[0].data)["message"] == "Empty String" + + +def test_update_pdp_without_security_pipeline(): + data = { + "name": "testuser", + "security_pipeline": [], + "keystone_project_id": "keystone_project_id", + "description": "description of testuser" + } + client = utilities.register_client() + req_update = update_pdp(client, data, "") + assert req_update[0].status_code == 500 + assert json.loads(req_update[0].data)["message"] == "Empty Container" \ No newline at end of file diff --git a/moon_manager/tests/unit_python/api/test_perimeter.py b/moon_manager/tests/unit_python/api/test_perimeter.py index db09780f..b13bb2ed 100644 --- a/moon_manager/tests/unit_python/api/test_perimeter.py +++ b/moon_manager/tests/unit_python/api/test_perimeter.py @@ -6,11 +6,8 @@ import api.utilities as utilities def get_subjects(client): req = client.get("/subjects") - assert req.status_code == 200 subjects = utilities.get_json(req.data) - assert isinstance(subjects, dict) - assert "subjects" in subjects - return subjects + return req, subjects def add_subjects(client, name): @@ -22,58 +19,72 @@ def add_subjects(client, name): } req = client.post("/subjects", data=json.dumps(data), headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 subjects = utilities.get_json(req.data) + return req, subjects + + +def delete_subject(client): + subjects = get_subjects(client) + for key, value in subjects[1]['subjects'].items(): + if value['name'] == "testuser": + req = client.delete("/subjects/{}".format(key)) + break + return req + + +def delete_subjects_without_perimeter_id(client): + req = client.delete("/subjects/{}".format("")) + return req + + +def test_perimeter_get_subject(): + client = utilities.register_client() + req, subjects = get_subjects(client) + assert req.status_code == 200 assert isinstance(subjects, dict) - key = list(subjects["subjects"].keys())[0] + assert "subjects" in subjects + + +def test_perimeter_add_subject(): + client = utilities.register_client() + req, subjects = add_subjects(client, "testuser") + assert req.status_code == 200 value = list(subjects["subjects"].values())[0] assert "subjects" in subjects - assert key == "1111111111111" - assert value['id'] == "1111111111111" - assert value['name'] == name - assert value["description"] == "description of {}".format(name) - assert value["email"] == "{}@moon".format(name) - return subjects + assert value['name'] == "testuser" + assert value["email"] == "{}@moon".format("testuser") -def add_subjects_without_name(client, name): - data = { - "name": name, - "description": "description of {}".format(name), - "password": "password for {}".format(name), - "email": "{}@moon".format(name) - } - req = client.post("/subjects", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) +def test_perimeter_add_subject_without_name(): + client = utilities.register_client() + req, subjects = add_subjects(client, "") assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" -def delete_subject(client, name): - subjects = get_subjects(client) - for key, value in subjects['subjects'].items(): - if value['name'] == name: - req = client.delete("/subjects/{}".format(key)) - assert req.status_code == 200 - break - subjects = get_subjects(client) - assert name not in [x['name'] for x in subjects["subjects"].values()] +def test_perimeter_add_subject_with_name_contain_spaces(): + client = utilities.register_client() + req, subjects = add_subjects(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" -def test_subject(): +def test_perimeter_delete_subject(): client = utilities.register_client() - get_subjects(client) - add_subjects(client, "testuser") - add_subjects_without_name(client, "") - delete_subject(client, "testuser") + req = delete_subject(client) + assert req.status_code == 200 + + +def test_perimeter_delete_subjects_without_perimeter_id(): + client = utilities.register_client() + req = delete_subjects_without_perimeter_id(client) + assert req.status_code == 500 def get_objects(client): req = client.get("/objects") - assert req.status_code == 200 objects = utilities.get_json(req.data) - assert isinstance(objects, dict) - assert "objects" in objects - return objects + return req, objects def add_objects(client, name): @@ -83,42 +94,71 @@ def add_objects(client, name): } req = client.post("/objects", data=json.dumps(data), headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 objects = utilities.get_json(req.data) - assert isinstance(objects, dict) - key = list(objects["objects"].keys())[0] - value = list(objects["objects"].values())[0] - assert "objects" in objects - assert value['name'] == name - assert value["description"] == "description of {}".format(name) - return objects + return req, objects -def delete_objects(client, name): +def delete_object(client): objects = get_objects(client) - for key, value in objects['objects'].items(): - if value['name'] == name: + for key, value in objects[1]['objects'].items(): + if value['name'] == "testuser": req = client.delete("/objects/{}".format(key)) - assert req.status_code == 200 break - objects = get_objects(client) - assert name not in [x['name'] for x in objects["objects"].values()] + return req + +def delete_objects_without_perimeter_id(client): + req = client.delete("/objects/{}".format("")) + return req -def test_objects(): + +def test_perimeter_get_object(): client = utilities.register_client() - get_objects(client) - add_objects(client, "testuser") - delete_objects(client, "testuser") + req, objects = get_objects(client) + assert req.status_code == 200 + assert isinstance(objects, dict) + assert "objects" in objects + + +def test_perimeter_add_object(): + client = utilities.register_client() + req, objects = add_objects(client, "testuser") + assert req.status_code == 200 + value = list(objects["objects"].values())[0] + assert "objects" in objects + assert value['name'] == "testuser" + + +def test_perimeter_add_object_without_name(): + client = utilities.register_client() + req, objects = add_objects(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_perimeter_add_object_with_name_contain_spaces(): + client = utilities.register_client() + req, objects = add_objects(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_perimeter_delete_object(): + client = utilities.register_client() + req = delete_object(client) + assert req.status_code == 200 + + +def test_perimeter_delete_objects_without_perimeter_id(): + client = utilities.register_client() + req = delete_objects_without_perimeter_id(client) + assert req.status_code == 500 def get_actions(client): req = client.get("/actions") - assert req.status_code == 200 actions = utilities.get_json(req.data) - assert isinstance(actions, dict) - assert "actions" in actions - return actions + return req, actions def add_actions(client, name): @@ -128,30 +168,63 @@ def add_actions(client, name): } req = client.post("/actions", data=json.dumps(data), headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 actions = utilities.get_json(req.data) - assert isinstance(actions, dict) - key = list(actions["actions"].keys())[0] - value = list(actions["actions"].values())[0] - assert "actions" in actions - assert value['name'] == name - assert value["description"] == "description of {}".format(name) - return actions + return req, actions -def delete_actions(client, name): +def delete_actions(client): actions = get_actions(client) - for key, value in actions['actions'].items(): - if value['name'] == name: + for key, value in actions[1]['actions'].items(): + if value['name'] == "testuser": req = client.delete("/actions/{}".format(key)) - assert req.status_code == 200 break - actions = get_actions(client) - assert name not in [x['name'] for x in actions["actions"].values()] + return req + +def delete_actions_without_perimeter_id(client): + req = client.delete("/actions/{}".format("")) + return req -def test_actions(): + +def test_perimeter_get_actions(): + client = utilities.register_client() + req, actions = get_actions(client) + assert req.status_code == 200 + assert isinstance(actions, dict) + assert "actions" in actions + + +def test_perimeter_add_actions(): client = utilities.register_client() - get_actions(client) - add_actions(client, "testuser") - delete_actions(client, "testuser") + req, actions = add_actions(client, "testuser") + assert req.status_code == 200 + value = list(actions["actions"].values())[0] + assert "actions" in actions + assert value['name'] == "testuser" + + +def test_perimeter_add_actions_without_name(): + client = utilities.register_client() + req, actions = add_actions(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_perimeter_add_actions_with_name_contain_spaces(): + client = utilities.register_client() + req, actions = add_actions(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_perimeter_delete_actions(): + client = utilities.register_client() + req = delete_actions(client) + assert req.status_code == 200 + + +def test_perimeter_delete_actions_without_perimeter_id(): + client = utilities.register_client() + req = delete_actions_without_perimeter_id(client) + assert req.status_code == 500 + diff --git a/moon_manager/tests/unit_python/api/test_rules.py b/moon_manager/tests/unit_python/api/test_rules.py index 0b302494..d12b7186 100644 --- a/moon_manager/tests/unit_python/api/test_rules.py +++ b/moon_manager/tests/unit_python/api/test_rules.py @@ -23,6 +23,35 @@ def add_rules(client, policy_id): return req, rules +def add_rules_without_meta_rule_id(client, policy_id): + data = { + "meta_rule_id": "", + "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"], + "instructions": ( + {"decision": "grant"}, + ), + "enabled": True + } + req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + rules = utilities.get_json(req.data) + return req, rules + + +def add_rules_without_rule(client, policy_id): + data = { + "meta_rule_id": "meta_rule_id1", + "instructions": ( + {"decision": "grant"}, + ), + "enabled": True + } + req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + rules = utilities.get_json(req.data) + return req, rules + + def delete_rules(client, policy_id, meta_rule_id): req = client.delete("/policies/{}/rules/{}".format(policy_id, meta_rule_id)) return req @@ -50,10 +79,37 @@ def test_add_rules(): assert value[id]["meta_rule_id"] == "meta_rule_id1" +def test_add_rules_without_policy_id(): + client = utilities.register_client() + req, rules = add_rules(client, None) + assert req.status_code == 500 + + +def test_add_rules_without_meta_rule_id(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, rules = add_rules_without_meta_rule_id(client, policy_id) + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty String' + + +def test_add_rules_without_rule(): + policy_id = utilities.get_policy_id() + client = utilities.register_client() + req, rules = add_rules_without_rule(client, policy_id) + assert req.status_code == 500 + + def test_delete_rules(): + client = utilities.register_client() + rules = delete_rules(client, "", "") + assert rules.status_code == 500 + + +def test_delete_rules_without_policy_id(): client = utilities.register_client() policy_id = utilities.get_policy_id() req, added_rules = get_rules(client, policy_id) id = added_rules["rules"]['rules'][0]['id'] - rules = delete_rules(client, policy_id, id) + rules = delete_rules(client, None, id) assert rules.status_code == 200 diff --git a/moon_manager/tests/unit_python/api/test_unit_models.py b/moon_manager/tests/unit_python/api/test_unit_models.py index 6f97b1ae..52cb2871 100644 --- a/moon_manager/tests/unit_python/api/test_unit_models.py +++ b/moon_manager/tests/unit_python/api/test_unit_models.py @@ -25,6 +25,42 @@ def add_models(client, name): return req, models +def update_model(client, name, model_id): + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": ["meta_rule_id1_update", "meta_rule_id2_update"] + } + req = client.patch("/models/{}".format(model_id), data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + models = utilities.get_json(req.data) + return req, models + + +def add_model_without_meta_rules_ids(client, name): + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [] + } + req = client.post("/models", data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + models = utilities.get_json(req.data) + return req, models + + +def update_model_without_meta_rules_ids(client, name): + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [] + } + req = client.patch("/models", data=json.dumps(data), + headers={'Content-Type': 'application/json'}) + models = utilities.get_json(req.data) + return req, models + + def delete_models(client, name): request, models = get_models(client) for key, value in models['models'].items(): @@ -47,6 +83,7 @@ def clean_models(): print(value) client.delete("/models/{}".format(key)) + def test_get_models(): client = utilities.register_client() req, models= get_models(client) @@ -79,3 +116,60 @@ def test_delete_models_without_id(): req = delete_models_without_id(client) assert req.status_code == 500 + +def test_add_model_with_empty_user(): + clean_models() + client = utilities.register_client() + req, models = add_models(client, "") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "Empty String" + + +def test_add_model_with_user_contain_space(): + clean_models() + client = utilities.register_client() + req, models = add_models(client, "test user") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == "String contains space" + + +def test_add_model_without_meta_rules(): + clean_models() + client = utilities.register_client() + req, meta_rules = add_model_without_meta_rules_ids(client, "testuser") + assert req.status_code == 500 + assert json.loads(req.data)["message"] == 'Empty Container' + + +def test_update_model(): + clean_models() + client = utilities.register_client() + req = add_models(client, "testuser") + model_id = list(req[1]['models'])[0] + req_update = update_model(client, "testuser", model_id) + assert req_update[0].status_code == 200 + value = list(req_update[1]["models"].values())[0] + assert value["meta_rules"][0] == "meta_rule_id1_update" + delete_models(client, "testuser") + + +def test_update_meta_rules_without_id(): + clean_models() + client = utilities.register_client() + req_update = update_model(client, "testuser", "") + assert req_update[0].status_code == 500 + + +def test_update_meta_rules_without_user(): + client = utilities.register_client() + req_update = update_model(client, "", "") + assert req_update[0].status_code == 500 + assert json.loads(req_update[0].data)["message"] == "Empty String" + + +def test_update_meta_rules_without_meta_rules(): + client = utilities.register_client() + req_update = update_model_without_meta_rules_ids(client, "testuser") + assert req_update[0].status_code == 500 + assert json.loads(req_update[0].data)["message"] == "Empty Container" + diff --git a/python_moonutilities/python_moonutilities/security_functions.py b/python_moonutilities/python_moonutilities/security_functions.py index 15cbc8be..84e9ab7d 100644 --- a/python_moonutilities/python_moonutilities/security_functions.py +++ b/python_moonutilities/python_moonutilities/security_functions.py @@ -22,7 +22,6 @@ __targets = {} def filter_input(func_or_str): - def __filter(string): if string and type(string) is str: return "".join(re.findall("[\w\- +]*", string)) @@ -82,15 +81,124 @@ def filter_input(func_or_str): return None +""" +To do should check value of Dictionary but it's dependent on from where it's coming +""" + + +def validate_data(data): + def __validate_string(string): + if not string: + raise ValueError('Empty String') + ''' + is it valid to contains space inbetween + + ''' + + if " " in string: + raise ValueError('String contains space') + + def __validate_list_or_tuple(container): + if not container: + raise ValueError('Empty Container') + for i in container: + validate_data(i) + + def __validate_dict(dictionary): + if not dictionary: + raise ValueError('Empty Dictionary') + for key in dictionary: + validate_data(dictionary[key]) + + if isinstance(data, str): + __validate_string(data) + elif isinstance(data, list) or isinstance(data, tuple): + __validate_list_or_tuple(data) + elif isinstance(data, dict): + __validate_dict(data) + else: + raise ValueError('Value is Not String or Container or Dictionary') + + +def validate_input(type, args_state=[], kwargs_state=[], body_state=[]): + """ + this fucntion works only on List or tuple or dictionary of Strings ,and String direct + Check if input of function is Valid or not, Valid if not has spaces and values is not None or empty. + + :param type: type of request if function is used as decorator + :param args_state: list of Booleans for args, + values must be order as target values of arguments, + True if None is not Allowed and False if is allowed + :param kwargs_state: list of Booleans for kwargs as order of input kwargs, + values must be order as target values of arguments, + True if None is not Allowed and False if is allowed + :param body_state: list of Booleans for arguments in body of request if request is post, + values must be order as target values of arguments, + True if None is not Allowed and False if is allowed + :return: + """ + + def validate_input_decorator(func): + def wrapped(*args, **kwargs): + + temp_args = [] + """ + this loop made to filter args from object class, + when put this function as decorator in function control + then there is copy of this class add to front of args + """ + for arg in args: + if isinstance(arg, str) == True or \ + isinstance(arg, list) == True or \ + isinstance(arg, dict) == True: + temp_args.append(arg) + + while len(args_state) < len(temp_args): + args_state.append(True) + + for i in range(0, len(temp_args)): + if args_state[i]: + validate_data(temp_args[i]) + + while len(kwargs_state) < len(kwargs): + kwargs_state.append(True) + counter = 0 + for i in kwargs: + if kwargs_state[counter]: + validate_data({i: kwargs[i]}) + + counter = counter + 1 + + if type == "post" or type == "patch": + body = request.json + while len(body_state) < len(body): + body_state.append(True) + counter = 0 + for i in body: + if body_state[counter]: + validate_data({i: body[i]}) + + counter = counter + 1 + + return func(*args, **kwargs) + + return wrapped + + return validate_input_decorator + + def enforce(action_names, object_name, **extra): """Fake version of the enforce decorator""" + def wrapper_func(func): def wrapper_args(*args, **kwargs): # LOG.info("kwargs={}".format(kwargs)) # kwargs['user_id'] = kwargs.pop('user_id', "admin") # LOG.info("Calling enforce on {} with args={} kwargs={}".format(func.__name__, args, kwargs)) return func(*args, **kwargs) + return wrapper_args + return wrapper_func @@ -221,4 +329,5 @@ def check_auth(function): user_id = kwargs.pop("user_id", token) result = function(*args, **kwargs, user_id=user_id) return result + return wrapper diff --git a/python_moonutilities/tests/unit_python/test_validated_input.py b/python_moonutilities/tests/unit_python/test_validated_input.py new file mode 100644 index 00000000..c8e681e9 --- /dev/null +++ b/python_moonutilities/tests/unit_python/test_validated_input.py @@ -0,0 +1,191 @@ +import pytest + + +def test_valid_string(): + from python_moonutilities.security_functions import validate_data + validate_data("CorrectString") + +def test_unvalid_string(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data("Notcorrect String") + + assert str(exception_info.value) == 'String contains space' + +def test_empty_string(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data("") + + assert str(exception_info.value) == 'Empty String' + + +def test_none_value(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(None) + + assert str(exception_info.value) == 'Value is Not String or Container or Dictionary' + + +def test_int_value(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(1) + + assert str(exception_info.value) == 'Value is Not String or Container or Dictionary' + + +def test_float_value(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(1.23) + + assert str(exception_info.value) == 'Value is Not String or Container or Dictionary' + + +def test_correct_list(): + from python_moonutilities.security_functions import validate_data + validate_data(["skjdnfa","dao","daosdjpw"]) + + +def test_correct_list(): + from python_moonutilities.security_functions import validate_data + validate_data(["skjdnfa"]) + + +def test_correct_instead_list(): + from python_moonutilities.security_functions import validate_data + validate_data([["skjdnfa","daswi"],[["daskdlw"],["daklwo"]],["dawl","afioa"],["dawno"]]) + + +def test_empty_list(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data([]) + + assert str(exception_info.value) == 'Empty Container' + + +def test_empty_list_inside_other_list(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(["dajiwdj",[]]) + + assert str(exception_info.value) == 'Empty Container' + + +def test_incorrect_string_inside_list(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(["dajiwdj",["dakwe","daow awoepa"]]) + + assert str(exception_info.value) == 'String contains space' + + +def test_empty_string_inside_list(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(["dajiwdj", ["dakwe", ""]]) + + assert str(exception_info.value) == 'Empty String' + + +def test_correct_tuples(): + from python_moonutilities.security_functions import validate_data + validate_data(("dasdw","dawdwa")) + + +def test_empty_tuples(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(()) + + assert str(exception_info.value) == 'Empty Container' + +def test_correct_tuple_of_tuple(): + from python_moonutilities.security_functions import validate_data + validate_data(("gjosjefa",("diwajdi","oejfoea"),(("jwdi","fjia"),("nfioa","ifao")))) + + +def test_incorrect_tuple(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(("djawo","dowa afw")) + + assert str(exception_info.value) == 'String contains space' + + +def test_correct_dictionary(): + from python_moonutilities.security_functions import validate_data + validate_data({"daiwdw":"dwioajd"}) + + +def test_incorrect_dictionary(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data({"daiwdw":"dwioa jd"}) + + assert str(exception_info.value) == 'String contains space' + +def test_empty_dictionary(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data({}) + + assert str(exception_info.value) == 'Empty Dictionary' + + +def test_correct_function_pass(): + from python_moonutilities.security_functions import validate_input + + @validate_input() + def temp_function(string,list,tuple): + if string!="teststring" : + raise ValueError("values which passed incorrect") + + temp_function("teststring",["teststring",["teststring"]],("teststring",("teststring"))) + +def test_incorrect_function_pass1(): + from python_moonutilities.security_functions import validate_input + + @validate_input() + def temp_function(string, list, tuple): + if string != "teststring": + raise ValueError("values which passed incorrect") + + with pytest.raises(Exception) as exception_info: + temp_function("teststring",list=["teststring", ["testst ring"]],tuple=("teststring", ("teststri ng"))) + + assert str(exception_info.value) == 'String contains space' + + +def test_incorrect_function_pass2(): + from python_moonutilities.security_functions import validate_input + + @validate_input() + def temp_function(string, list, dictionary): + if string != "teststring": + raise ValueError("values which passed incorrect") + + with pytest.raises(Exception) as exception_info: + temp_function("teststring", ["teststring", ["teststri ng"]], {"teststring": ("teststring")}) + + assert str(exception_info.value) == 'String contains space' + + +def test_incorrect_function_pass3(): + from python_moonutilities.security_functions import validate_input + + class x: + @validate_input() + def temp_function(string, list, dictionary): + if string != "teststring": + raise ValueError("values which passed incorrect") + + e=x; + + with pytest.raises(Exception) as exception_info: + e.temp_function("teststring", ["teststring", ["teststri ng"]], {"teststring": ("teststring")}) + + assert str(exception_info.value) == 'String contains space' -- cgit 1.2.3-korg