aboutsummaryrefslogtreecommitdiffstats
path: root/moon_manager
diff options
context:
space:
mode:
authorThomas Duval <thomas.duval@orange.com>2018-10-05 16:54:37 +0200
committerThomas Duval <thomas.duval@orange.com>2018-10-05 16:58:48 +0200
commit2e35a7e46f0929438c1c206e3116caa829f07dc6 (patch)
tree759a83b3dfefe70faeada1c3af7377f4cd89b8eb /moon_manager
parent2dbe655587ca98b67c1a3e3798c63fd47229adc0 (diff)
Update code to 4.6 official version
Change-Id: Ibd0da0e476e24b2685f54693efc11f7a58d40a62
Diffstat (limited to 'moon_manager')
-rw-r--r--moon_manager/.gitignore104
-rw-r--r--moon_manager/Changelog35
-rw-r--r--moon_manager/moon_manager/__init__.py2
-rw-r--r--moon_manager/moon_manager/api/assignments.py96
-rw-r--r--moon_manager/moon_manager/api/base_exception.py3
-rw-r--r--moon_manager/moon_manager/api/data.py36
-rw-r--r--moon_manager/moon_manager/api/generic.py7
-rw-r--r--moon_manager/moon_manager/api/json_export.py109
-rw-r--r--moon_manager/moon_manager/api/json_import.py186
-rw-r--r--moon_manager/moon_manager/api/json_utils.py87
-rw-r--r--moon_manager/moon_manager/api/meta_data.py12
-rw-r--r--moon_manager/moon_manager/api/meta_rules.py10
-rw-r--r--moon_manager/moon_manager/api/models.py6
-rw-r--r--moon_manager/moon_manager/api/pdp.py14
-rw-r--r--moon_manager/moon_manager/api/perimeter.py86
-rw-r--r--moon_manager/moon_manager/api/policies.py9
-rw-r--r--moon_manager/moon_manager/api/rules.py8
-rw-r--r--moon_manager/moon_manager/api/slaves.py7
-rw-r--r--moon_manager/moon_manager/http_server.py8
-rw-r--r--moon_manager/moon_manager/server.py1
-rw-r--r--moon_manager/tests/unit_python/api/import_export_utilities.py36
-rw-r--r--moon_manager/tests/unit_python/api/test_assignement.py280
-rw-r--r--moon_manager/tests/unit_python/api/test_data.py84
-rw-r--r--moon_manager/tests/unit_python/api/test_import.py20
-rw-r--r--moon_manager/tests/unit_python/api/test_meta_data.py116
-rw-r--r--moon_manager/tests/unit_python/api/test_meta_rules.py370
-rw-r--r--moon_manager/tests/unit_python/api/test_pdp.py57
-rw-r--r--moon_manager/tests/unit_python/api/test_perimeter.py935
-rw-r--r--moon_manager/tests/unit_python/api/test_policies.py287
-rw-r--r--moon_manager/tests/unit_python/api/test_rules.py47
-rw-r--r--moon_manager/tests/unit_python/api/test_unit_models.py226
-rw-r--r--moon_manager/tests/unit_python/conftest.py22
-rw-r--r--moon_manager/tests/unit_python/helpers/data_builder.py79
-rw-r--r--moon_manager/tests/unit_python/helpers/data_helper.py6
-rw-r--r--moon_manager/tests/unit_python/helpers/model_helper.py7
-rw-r--r--moon_manager/tests/unit_python/helpers/policy_helper.py4
-rw-r--r--moon_manager/tests/unit_python/requirements.txt4
37 files changed, 2735 insertions, 671 deletions
diff --git a/moon_manager/.gitignore b/moon_manager/.gitignore
new file mode 100644
index 00000000..894a44cc
--- /dev/null
+++ b/moon_manager/.gitignore
@@ -0,0 +1,104 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# pyenv
+.python-version
+
+# celery beat schedule file
+celerybeat-schedule
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
diff --git a/moon_manager/Changelog b/moon_manager/Changelog
index 56521a0e..1fb9ac08 100644
--- a/moon_manager/Changelog
+++ b/moon_manager/Changelog
@@ -31,7 +31,7 @@ CHANGES
4.5.2-1
-----
-integrating validtion to send mandatory key names
+- integrating validation to send mandatory key names
4.5.3
-----
@@ -39,4 +39,35 @@ integrating validtion to send mandatory key names
- fixing test cases to assert on the expected exception after removing try-catch
- allow 404 to be catched from our side instead of flask itself
- revert the params in the get/post/patch/delete to be by default = None, so that we could catch the param if it was None
-instead of having not found url if the param is mandatory \ No newline at end of file
+instead of having not found url if the param is mandatory
+
+4.5.4
+-----
+- fixing test cases after validation dependencies added in moondb
+
+4.5.5
+-----
+- removing validation on meta_rule categories
+- Update to python_moonutilities 1.4.17 and fix tests
+- adding extra test cases for update requests
+- adding None to requests ( to avoid request not found)
+- removing validation on categories, meta_rules so that can be added empty
+
+4.5.5-1
+-------
+- Update to python_moonutilities 1.4.18
+
+4.5.5-2
+-------
+- Update to python_moonutilities 1.4.19
+
+4.5.6
+----
+apply pyLint
+adding extra test cases for policy update
+- separate perimeter add/update with validation
+
+4.6.0
+-----
+- Add a connection to the Update endpoint in Wrapper
+>>>>>>> Stashed changes
diff --git a/moon_manager/moon_manager/__init__.py b/moon_manager/moon_manager/__init__.py
index 205f6d8c..f0887748 100644
--- a/moon_manager/moon_manager/__init__.py
+++ b/moon_manager/moon_manager/__init__.py
@@ -3,4 +3,4 @@
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
-__version__ = "4.5.3"
+__version__ = "4.6.0"
diff --git a/moon_manager/moon_manager/api/assignments.py b/moon_manager/moon_manager/api/assignments.py
index 426789e6..9bc54b2d 100644
--- a/moon_manager/moon_manager/api/assignments.py
+++ b/moon_manager/moon_manager/api/assignments.py
@@ -6,10 +6,11 @@
Assignments allow to connect data with elements of perimeter
"""
-
+import flask
from flask import request
from flask_restful import Resource
import logging
+import requests
from python_moonutilities.security_functions import check_auth
from python_moondb.core import PolicyManager
from python_moonutilities.security_functions import validate_input
@@ -19,6 +20,35 @@ __version__ = "4.3.2"
logger = logging.getLogger("moon.manager.api." + __name__)
+def invalidate_data_in_slaves(
+ policy_id,
+ perimeter_id,
+ category_id,
+ data_id):
+ slaves = requests.get("http://{}/slaves".format(request.host)).json().get("slaves")
+ for slave in slaves:
+ if not slave.get("configured", False):
+ continue
+ try:
+ update = requests.put("http://{}:{}/update".format(
+ slave.get("wrapper_name"), slave.get("internal_port")),
+ data={
+ "policy_id": policy_id,
+ "perimeter_id": perimeter_id,
+ "category_id": category_id,
+ "data_id": data_id
+ },
+ timeout=1
+ )
+ logger.info("result {} {}:{} = {}".format(
+ update.status_code,
+ slave.get("wrapper_name"),
+ slave.get("internal_port"),
+ update.text))
+ except requests.exceptions.ConnectionError:
+ logger.warning("Cannot reach {}:{}".format(slave.get("wrapper_name"), slave.get("port")))
+
+
class SubjectAssignments(Resource):
"""
Endpoint for subject assignment requests
@@ -32,9 +62,9 @@ class SubjectAssignments(Resource):
"/policies/<string:uuid>/subject_assignments/<string:perimeter_id>/<string:category_id>/<string:data_id>",
)
- @validate_input("get", kwargs_state=[True, False, False,False,False])
+ @validate_input("get", kwargs_state=[True, False, False, False, False])
@check_auth
- def get(self, uuid, perimeter_id=None, category_id=None,
+ def get(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Retrieve all subject assignments or a specific one for a given policy
@@ -60,9 +90,10 @@ class SubjectAssignments(Resource):
return {"subject_assignments": data}
- @validate_input("post", kwargs_state=[True, False, False, False, False], body_state={"id":True, "category_id":True, "data_id":True})
+ @validate_input("post", kwargs_state=[True, False, False, False, False],
+ body_state={"id": True, "category_id": True, "data_id": True})
@check_auth
- def post(self, uuid, perimeter_id=None, category_id=None,
+ def post(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Create a subject assignment.
@@ -93,11 +124,17 @@ class SubjectAssignments(Resource):
user_id=user_id, policy_id=uuid,
subject_id=perimeter_id, category_id=category_id,
data_id=data_id)
+ invalidate_data_in_slaves(
+ policy_id=uuid,
+ perimeter_id=perimeter_id,
+ category_id=category_id,
+ data_id=data_id)
+
return {"subject_assignments": data}
@validate_input("delete", kwargs_state=[True, True, True, True, False])
@check_auth
- def delete(self, uuid, perimeter_id=None, category_id=None,
+ def delete(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Delete a subject assignment for a given policy
@@ -117,6 +154,11 @@ class SubjectAssignments(Resource):
user_id=user_id, policy_id=uuid,
subject_id=perimeter_id, category_id=category_id,
data_id=data_id)
+ invalidate_data_in_slaves(
+ policy_id=uuid,
+ perimeter_id=perimeter_id,
+ category_id=category_id,
+ data_id=data_id)
return {"result": True}
@@ -134,9 +176,9 @@ class ObjectAssignments(Resource):
"/policies/<string:uuid>/object_assignments/<string:perimeter_id>/<string:category_id>/<string:data_id>",
)
- @validate_input("get", kwargs_state=[True, False, False,False,False])
+ @validate_input("get", kwargs_state=[True, False, False, False, False])
@check_auth
- def get(self, uuid, perimeter_id=None, category_id=None,
+ def get(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Retrieve all object assignment or a specific one for a given policy
@@ -162,9 +204,10 @@ class ObjectAssignments(Resource):
return {"object_assignments": data}
- @validate_input("post", kwargs_state=[True, False, False, False, False], body_state={"id":True, "category_id":True, "data_id":True})
+ @validate_input("post", kwargs_state=[True, False, False, False, False],
+ body_state={"id": True, "category_id": True, "data_id": True})
@check_auth
- def post(self, uuid, perimeter_id=None, category_id=None,
+ def post(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Create an object assignment.
@@ -196,12 +239,17 @@ class ObjectAssignments(Resource):
user_id=user_id, policy_id=uuid,
object_id=perimeter_id, category_id=category_id,
data_id=data_id)
+ invalidate_data_in_slaves(
+ policy_id=uuid,
+ perimeter_id=perimeter_id,
+ category_id=category_id,
+ data_id=data_id)
return {"object_assignments": data}
@validate_input("delete", kwargs_state=[True, True, True, True, False])
@check_auth
- def delete(self, uuid, perimeter_id=None, category_id=None,
+ def delete(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Delete a object assignment for a given policy
@@ -220,6 +268,11 @@ class ObjectAssignments(Resource):
user_id=user_id, policy_id=uuid,
object_id=perimeter_id, category_id=category_id,
data_id=data_id)
+ invalidate_data_in_slaves(
+ policy_id=uuid,
+ perimeter_id=perimeter_id,
+ category_id=category_id,
+ data_id=data_id)
return {"result": True}
@@ -237,9 +290,9 @@ class ActionAssignments(Resource):
"/policies/<string:uuid>/action_assignments/<string:perimeter_id>/<string:category_id>/<string:data_id>",
)
- @validate_input("get", kwargs_state=[True, False, False,False,False])
+ @validate_input("get", kwargs_state=[True, False, False, False, False])
@check_auth
- def get(self, uuid, perimeter_id=None, category_id=None,
+ def get(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Retrieve all action assignment or a specific one for a given policy
@@ -264,9 +317,10 @@ class ActionAssignments(Resource):
return {"action_assignments": data}
- @validate_input("post", kwargs_state=[True, False, False, False, False], body_state={"id":True, "category_id":True, "data_id":True})
+ @validate_input("post", kwargs_state=[True, False, False, False, False],
+ body_state={"id": True, "category_id": True, "data_id": True})
@check_auth
- def post(self, uuid, perimeter_id=None, category_id=None,
+ def post(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Create an action assignment.
@@ -298,12 +352,17 @@ class ActionAssignments(Resource):
user_id=user_id, policy_id=uuid,
action_id=perimeter_id, category_id=category_id,
data_id=data_id)
+ invalidate_data_in_slaves(
+ policy_id=uuid,
+ perimeter_id=perimeter_id,
+ category_id=category_id,
+ data_id=data_id)
return {"action_assignments": data}
@validate_input("delete", kwargs_state=[True, True, True, True, False])
@check_auth
- def delete(self, uuid, perimeter_id=None, category_id=None,
+ def delete(self, uuid=None, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
"""Delete a action assignment for a given policy
@@ -323,5 +382,10 @@ class ActionAssignments(Resource):
user_id=user_id, policy_id=uuid,
action_id=perimeter_id, category_id=category_id,
data_id=data_id)
+ invalidate_data_in_slaves(
+ policy_id=uuid,
+ perimeter_id=perimeter_id,
+ category_id=category_id,
+ data_id=data_id)
return {"result": True}
diff --git a/moon_manager/moon_manager/api/base_exception.py b/moon_manager/moon_manager/api/base_exception.py
index 0af3b6d0..0a414a59 100644
--- a/moon_manager/moon_manager/api/base_exception.py
+++ b/moon_manager/moon_manager/api/base_exception.py
@@ -1,4 +1,3 @@
-
class BaseException(Exception):
def __init__(self, message):
self._code = 500
@@ -15,4 +14,4 @@ class BaseException(Exception):
return self._message
def __str__(self):
- return "Error " + str(self._code) + " " + self.__class__.__name__ + ': ' + self.message \ No newline at end of file
+ return "Error " + str(self._code) + " " + self.__class__.__name__ + ': ' + self.message
diff --git a/moon_manager/moon_manager/api/data.py b/moon_manager/moon_manager/api/data.py
index d887ac2b..92d7b2c6 100644
--- a/moon_manager/moon_manager/api/data.py
+++ b/moon_manager/moon_manager/api/data.py
@@ -28,13 +28,12 @@ class SubjectData(Resource):
"/policies/<string:uuid>/subject_data",
"/policies/<string:uuid>/subject_data/",
"/policies/<string:uuid>/subject_data/<string:category_id>",
- "/policies/<string:uuid>/subject_data/<string:category_id>/"
- "<string:data_id>",
+ "/policies/<string:uuid>/subject_data/<string:category_id>/<string:data_id>",
)
@validate_input("get", kwargs_state=[True, False, False, False])
@check_auth
- def get(self, uuid, category_id=None, data_id=None, user_id=None):
+ def get(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all subject categories or a specific one if data_id is given
for a given policy
@@ -63,9 +62,9 @@ class SubjectData(Resource):
return {"subject_data": data}
- @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name":True})
+ @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name": True})
@check_auth
- def post(self, uuid, category_id=None, data_id=None, user_id=None):
+ def post(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Create or update a subject.
:param uuid: uuid of the policy
@@ -90,14 +89,14 @@ class SubjectData(Resource):
"""
data = PolicyManager.set_subject_data(user_id=user_id,
policy_id=uuid,
- category_id=category_id,
- value=request.json)
+ category_id=category_id,
+ value=request.json)
return {"subject_data": data}
@validate_input("delete", kwargs_state=[True, False, False, False])
@check_auth
- def delete(self, uuid, category_id=None, data_id=None, user_id=None):
+ def delete(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Delete a subject for a given policy
:param uuid: uuid of the policy
@@ -113,6 +112,7 @@ class SubjectData(Resource):
logger.info("api.delete {} {}".format(uuid, data_id))
data = PolicyManager.delete_subject_data(user_id=user_id,
policy_id=uuid,
+ category_id=category_id,
data_id=data_id)
return {"result": True}
@@ -133,7 +133,7 @@ class ObjectData(Resource):
@validate_input("get", kwargs_state=[True, False, False, False])
@check_auth
- def get(self, uuid, category_id=None, data_id=None, user_id=None):
+ 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
for a given policy
@@ -160,9 +160,9 @@ class ObjectData(Resource):
return {"object_data": data}
- @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name":True})
+ @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name": True})
@check_auth
- def post(self, uuid, category_id=None, data_id=None, user_id=None):
+ def post(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Create or update a object.
:param uuid: uuid of the policy
@@ -194,7 +194,7 @@ class ObjectData(Resource):
@validate_input("delete", kwargs_state=[True, False, False, False])
@check_auth
- def delete(self, uuid, category_id=None, data_id=None, user_id=None):
+ def delete(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Delete a object for a given policy
:param uuid: uuid of the policy
@@ -209,6 +209,7 @@ class ObjectData(Resource):
"""
data = PolicyManager.delete_object_data(user_id=user_id,
policy_id=uuid,
+ category_id=category_id,
data_id=data_id)
return {"result": True}
@@ -229,7 +230,7 @@ class ActionData(Resource):
@validate_input("get", kwargs_state=[True, False, False, False])
@check_auth
- def get(self, uuid, category_id=None, data_id=None, user_id=None):
+ 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
for a given policy
@@ -256,9 +257,9 @@ class ActionData(Resource):
return {"action_data": data}
- @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name":True})
+ @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name": True})
@check_auth
- def post(self, uuid, category_id=None, data_id=None, user_id=None):
+ def post(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Create or update a action.
:param uuid: uuid of the policy
@@ -289,7 +290,7 @@ class ActionData(Resource):
@validate_input("delete", kwargs_state=[True, False, False, False])
@check_auth
- def delete(self, uuid, category_id=None, data_id=None, user_id=None):
+ def delete(self, uuid=None, category_id=None, data_id=None, user_id=None):
"""Delete a action for a given policy
:param uuid: uuid of the policy
@@ -304,8 +305,7 @@ class ActionData(Resource):
"""
data = PolicyManager.delete_action_data(user_id=user_id,
policy_id=uuid,
+ category_id=category_id,
data_id=data_id)
return {"result": True}
-
-
diff --git a/moon_manager/moon_manager/api/generic.py b/moon_manager/moon_manager/api/generic.py
index c79520f7..721f6213 100644
--- a/moon_manager/moon_manager/api/generic.py
+++ b/moon_manager/moon_manager/api/generic.py
@@ -122,13 +122,16 @@ class API(Resource):
api_desc[api_name]["version"] = group_api_obj.__version__
object_list = list(filter(lambda x: "__" not in x,
dir(group_api_obj)))
- for obj in map(lambda x: eval("moon_manager.api.{}.{}".format(api_name, x)), object_list):
+ for obj in map(lambda x: eval("moon_manager.api.{}.{}".format(api_name, x)),
+ object_list):
if "__urls__" in dir(obj):
api_desc[api_name][obj.__name__] = dict()
api_desc[api_name][obj.__name__]["urls"] = obj.__urls__
api_desc[api_name][obj.__name__]["methods"] = dict()
for _method in filter(lambda x: x in __methods, dir(obj)):
- docstring = eval("moon_manager.api.{}.{}.{}.__doc__".format(api_name, obj.__name__, _method))
+ docstring = eval(
+ "moon_manager.api.{}.{}.{}.__doc__".format(api_name, obj.__name__,
+ _method))
api_desc[api_name][obj.__name__]["methods"][_method] = docstring
api_desc[api_name][obj.__name__]["description"] = str(obj.__doc__)
if group_id in api_desc:
diff --git a/moon_manager/moon_manager/api/json_export.py b/moon_manager/moon_manager/api/json_export.py
index 1d3643e7..069e5884 100644
--- a/moon_manager/moon_manager/api/json_export.py
+++ b/moon_manager/moon_manager/api/json_export.py
@@ -17,7 +17,6 @@ logger = logging.getLogger("moon.manager.api." + __name__)
class JsonExport(Resource):
-
__urls__ = (
"/export",
"/export/",
@@ -35,22 +34,37 @@ class JsonExport(Resource):
rule_dict = dict()
JsonUtils.copy_field_if_exists(rule, rule_dict, "instructions", dict)
JsonUtils.copy_field_if_exists(rule, rule_dict, "enabled", True)
- JsonUtils.convert_id_to_name(rule["meta_rule_id"], rule_dict, "meta_rule", "meta_rule", ModelManager, self._user_id)
- JsonUtils.convert_id_to_name(policy_key, rule_dict, "policy", "policy", PolicyManager, self._user_id)
+ JsonUtils.convert_id_to_name(rule["meta_rule_id"], rule_dict, "meta_rule",
+ "meta_rule", ModelManager, self._user_id)
+ JsonUtils.convert_id_to_name(policy_key, rule_dict, "policy", "policy",
+ PolicyManager, self._user_id)
ids = rule["rule"]
rule_description = dict()
meta_rule = ModelManager.get_meta_rules(self._user_id, rule["meta_rule_id"])
meta_rule = [v for v in meta_rule.values()]
meta_rule = meta_rule[0]
- index_subject_data = len(meta_rule["subject_categories"])-1
- index_object_data = len(meta_rule["subject_categories"]) + len(meta_rule["object_categories"])-1
- index_action_data = len(meta_rule["subject_categories"]) + len(meta_rule["object_categories"]) + len(meta_rule["action_categories"])-1
- ids_subject_data = [ids[0]] if len(meta_rule["subject_categories"]) == 1 else ids[0:index_subject_data]
- ids_object_data = [ids[index_object_data]] if len(meta_rule["object_categories"]) == 1 else ids[index_subject_data+1:index_object_data]
- ids_action_date = [ids[index_action_data]] if len(meta_rule["action_categories"]) == 1 else ids[index_object_data+1:index_action_data]
- JsonUtils.convert_ids_to_names(ids_subject_data, rule_description, "subject_data", "subject_data", PolicyManager, self._user_id, policy_key)
- JsonUtils.convert_ids_to_names(ids_object_data, rule_description, "object_data", "object_data", PolicyManager, self._user_id, policy_key)
- JsonUtils.convert_ids_to_names(ids_action_date, rule_description, "action_data", "action_data", PolicyManager, self._user_id, policy_key)
+ index_subject_data = len(meta_rule["subject_categories"]) - 1
+ index_object_data = len(meta_rule["subject_categories"]) + len(
+ meta_rule["object_categories"]) - 1
+ index_action_data = len(meta_rule["subject_categories"]) + len(
+ meta_rule["object_categories"]) + len(meta_rule["action_categories"]) - 1
+ ids_subject_data = [ids[0]] if len(meta_rule["subject_categories"]) == 1 else ids[
+ 0:index_subject_data]
+ ids_object_data = [ids[index_object_data]] if len(
+ meta_rule["object_categories"]) == 1 else ids[
+ index_subject_data + 1:index_object_data]
+ ids_action_date = [ids[index_action_data]] if len(
+ meta_rule["action_categories"]) == 1 else ids[
+ index_object_data + 1:index_action_data]
+ JsonUtils.convert_ids_to_names(ids_subject_data, rule_description, "subject_data",
+ "subject_data", PolicyManager, self._user_id,
+ policy_key)
+ JsonUtils.convert_ids_to_names(ids_object_data, rule_description, "object_data",
+ "object_data", PolicyManager, self._user_id,
+ policy_key)
+ JsonUtils.convert_ids_to_names(ids_action_date, rule_description, "action_data",
+ "action_data", PolicyManager, self._user_id,
+ policy_key)
rule_dict["rule"] = rule_description
rules_array.append(rule_dict)
@@ -62,13 +76,20 @@ class JsonExport(Resource):
meta_rules_array = []
# logger.info(meta_rules)
for meta_rule_key in meta_rules:
- #logger.info(meta_rules[meta_rule_key])
+ # logger.info(meta_rules[meta_rule_key])
meta_rule_dict = dict()
JsonUtils.copy_field_if_exists(meta_rules[meta_rule_key], meta_rule_dict, "name", str)
- JsonUtils.copy_field_if_exists(meta_rules[meta_rule_key], meta_rule_dict, "description", str)
- JsonUtils.convert_ids_to_names(meta_rules[meta_rule_key]["subject_categories"], meta_rule_dict, "subject_categories", "subject_category", ModelManager, self._user_id)
- JsonUtils.convert_ids_to_names(meta_rules[meta_rule_key]["object_categories"], meta_rule_dict, "object_categories", "object_category", ModelManager, self._user_id)
- JsonUtils.convert_ids_to_names(meta_rules[meta_rule_key]["action_categories"], meta_rule_dict, "action_categories", "action_category", ModelManager, self._user_id)
+ JsonUtils.copy_field_if_exists(meta_rules[meta_rule_key], meta_rule_dict, "description",
+ str)
+ JsonUtils.convert_ids_to_names(meta_rules[meta_rule_key]["subject_categories"],
+ meta_rule_dict, "subject_categories", "subject_category",
+ ModelManager, self._user_id)
+ JsonUtils.convert_ids_to_names(meta_rules[meta_rule_key]["object_categories"],
+ meta_rule_dict, "object_categories", "object_category",
+ ModelManager, self._user_id)
+ JsonUtils.convert_ids_to_names(meta_rules[meta_rule_key]["action_categories"],
+ meta_rule_dict, "action_categories", "action_category",
+ ModelManager, self._user_id)
logger.info("Exporting meta rule {}".format(meta_rule_dict))
meta_rules_array.append(meta_rule_dict)
if len(meta_rules_array) > 0:
@@ -80,12 +101,20 @@ class JsonExport(Resource):
element_assignments_array = []
for policy_key in policies:
assignments = export_method_data(self._user_id, policy_key)
- #logger.info(assignments)
+ # logger.info(assignments)
for assignment_key in assignments:
assignment_dict = dict()
- JsonUtils.convert_id_to_name(assignments[assignment_key][type_element + "_id"], assignment_dict, type_element, type_element , PolicyManager, self._user_id, policy_key)
- JsonUtils.convert_id_to_name(assignments[assignment_key]["category_id"], assignment_dict, "category", type_element + "_category", ModelManager, self._user_id, policy_key)
- JsonUtils.convert_ids_to_names(assignments[assignment_key]["assignments"], assignment_dict, "assignments", type_element + "_data", PolicyManager, self._user_id, policy_key)
+ JsonUtils.convert_id_to_name(assignments[assignment_key][type_element + "_id"],
+ assignment_dict, type_element, type_element,
+ PolicyManager, self._user_id, policy_key)
+ JsonUtils.convert_id_to_name(assignments[assignment_key]["category_id"],
+ assignment_dict, "category",
+ type_element + "_category", ModelManager,
+ self._user_id, policy_key)
+ JsonUtils.convert_ids_to_names(assignments[assignment_key]["assignments"],
+ assignment_dict, "assignments",
+ type_element + "_data", PolicyManager, self._user_id,
+ policy_key)
element_assignments_array.append(assignment_dict)
logger.info("Exporting {} assignment {}".format(type_element, assignment_dict))
if len(element_assignments_array) > 0:
@@ -97,7 +126,7 @@ class JsonExport(Resource):
element_datas_array = []
for policy_key in policies:
datas = export_method_data(self._user_id, policy_key)
- #logger.info("data found : {}".format(datas))
+ # logger.info("data found : {}".format(datas))
for data_group in datas:
policy_id = data_group["policy_id"]
category_id = data_group["category_id"]
@@ -105,14 +134,21 @@ class JsonExport(Resource):
for data_key in data_group["data"]:
data_dict = dict()
if type_element == 'subject':
- JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict, "name", str)
- JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict, "description", str)
+ JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict,
+ "name", str)
+ JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict,
+ "description", str)
else:
- JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict, "name", str)
- JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict, "description", str)
+ JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict,
+ "name", str)
+ JsonUtils.copy_field_if_exists(data_group["data"][data_key], data_dict,
+ "description", str)
- JsonUtils.convert_id_to_name(policy_id, data_dict, "policy", "policy", PolicyManager, self._user_id)
- JsonUtils.convert_id_to_name(category_id, data_dict, "category", type_element + "_category", ModelManager, self._user_id, policy_key)
+ JsonUtils.convert_id_to_name(policy_id, data_dict, "policy", "policy",
+ PolicyManager, self._user_id)
+ JsonUtils.convert_id_to_name(category_id, data_dict, "category",
+ type_element + "_category", ModelManager,
+ self._user_id, policy_key)
logger.info("Exporting {} data {}".format(type_element, data_dict))
element_datas_array.append(data_dict)
@@ -125,8 +161,10 @@ class JsonExport(Resource):
element_categories_array = []
for element_category_key in element_categories:
element_category = dict()
- JsonUtils.copy_field_if_exists(element_categories[element_category_key], element_category, "name", str)
- JsonUtils.copy_field_if_exists(element_categories[element_category_key], element_category, "description", str)
+ JsonUtils.copy_field_if_exists(element_categories[element_category_key],
+ element_category, "name", str)
+ JsonUtils.copy_field_if_exists(element_categories[element_category_key],
+ element_category, "description", str)
element_categories_array.append(element_category)
logger.info("Exporting {} category {}".format(type_element, element_category))
if len(element_categories_array) > 0:
@@ -140,7 +178,7 @@ class JsonExport(Resource):
for policy_key in policies:
elements = export_method(self._user_id, policy_key)
for element_key in elements:
- #logger.info("Exporting {}".format(elements[element_key]))
+ # logger.info("Exporting {}".format(elements[element_key]))
element = dict()
JsonUtils.copy_field_if_exists(elements[element_key], element, "name", str)
JsonUtils.copy_field_if_exists(elements[element_key], element, "description", str)
@@ -149,7 +187,8 @@ class JsonExport(Resource):
element["policies"] = []
element_dict[element["name"]] = element
current_element = element_dict[element["name"]]
- current_element["policies"].append({"name": JsonUtils.convert_id_to_name_string(policy_key, "policy", PolicyManager, self._user_id)})
+ current_element["policies"].append({"name": JsonUtils.convert_id_to_name_string(
+ policy_key, "policy", PolicyManager, self._user_id)})
for key in element_dict:
logger.info("Exporting {} {}".format(type_element, element_dict[key]))
@@ -166,7 +205,8 @@ class JsonExport(Resource):
JsonUtils.copy_field_if_exists(policies[policy_key], policy, "name", str)
JsonUtils.copy_field_if_exists(policies[policy_key], policy, "genre", str)
JsonUtils.copy_field_if_exists(policies[policy_key], policy, "description", str)
- JsonUtils.convert_id_to_name(policies[policy_key]["model_id"], policy, "model", "model", ModelManager, self._user_id)
+ JsonUtils.convert_id_to_name(policies[policy_key]["model_id"], policy, "model", "model",
+ ModelManager, self._user_id)
logger.info("Exporting policy {}".format(policy))
policies_array.append(policy)
if len(policies_array) > 0:
@@ -180,7 +220,8 @@ class JsonExport(Resource):
JsonUtils.copy_field_if_exists(models[model_key], model, "name", str)
JsonUtils.copy_field_if_exists(models[model_key], model, "description", str)
# logger.info(models[model_key]["meta_rules"])
- JsonUtils.convert_ids_to_names(models[model_key]["meta_rules"], model, "meta_rules", "meta_rule", ModelManager, self._user_id)
+ JsonUtils.convert_ids_to_names(models[model_key]["meta_rules"], model, "meta_rules",
+ "meta_rule", ModelManager, self._user_id)
logger.info("Exporting model {}".format(model))
models_array.append(model)
if len(models_array) > 0:
diff --git a/moon_manager/moon_manager/api/json_import.py b/moon_manager/moon_manager/api/json_import.py
index e57a27c1..05f4a0c0 100644
--- a/moon_manager/moon_manager/api/json_import.py
+++ b/moon_manager/moon_manager/api/json_import.py
@@ -19,7 +19,6 @@ from python_moondb.core import PDPManager
from python_moondb.core import PolicyManager
from python_moondb.core import ModelManager
-
__version__ = "4.5.0"
logger = logging.getLogger("moon.manager.api." + __name__)
@@ -32,64 +31,61 @@ CATEGORIES_CALLBACK = 3
class ForbiddenOverride(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(ForbiddenOverride, self).__init__(message)
class UnknownPolicy(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(UnknownPolicy, self).__init__(message)
class UnknownModel(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(UnknownModel, self).__init__(message)
class UnknownData(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(UnknownData, self).__init__(message)
class MissingPolicy(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(MissingPolicy, self).__init__(message)
class InvalidJson(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(InvalidJson, self).__init__(message)
class JsonImport(Resource):
-
__urls__ = (
"/import",
"/import/",
)
- def _reorder_rules_ids(self, rule, ordered_perimeter_categories_ids, json_data_ids, policy_id, get_function):
- ordered_json_ids = [None]*len(ordered_perimeter_categories_ids)
+ def _reorder_rules_ids(self, rule, ordered_perimeter_categories_ids, json_data_ids, policy_id,
+ get_function):
+ ordered_json_ids = [None] * len(ordered_perimeter_categories_ids)
for json_id in json_data_ids:
data = get_function(self._user_id, policy_id, data_id=json_id)
data = data[0]
if data["category_id"] not in ordered_perimeter_categories_ids:
- raise InvalidJson("The category id {} of the rule {} does not match the meta rule".format(
- data["category_id"], rule))
- if ordered_json_ids[ordered_perimeter_categories_ids.index(data["category_id"])] is not None:
- raise InvalidJson("The category id {} of the rule {} shall not be used twice in the same rule".format(
- data["category_id"], rule))
+ raise InvalidJson(
+ "The category id {} of the rule {} does not match the meta rule".format(
+ data["category_id"], rule))
+ if ordered_json_ids[
+ ordered_perimeter_categories_ids.index(data["category_id"])] is not None:
+ raise InvalidJson(
+ "The category id {} of the rule {} shall not be used twice in the same rule".format(
+ data["category_id"], rule))
ordered_json_ids[ordered_perimeter_categories_ids.index(data["category_id"])] = json_id
logger.info(ordered_json_ids)
return ordered_json_ids
@@ -101,30 +97,46 @@ class JsonImport(Resource):
for json_rule in json_rules:
json_to_use = dict()
JsonUtils.copy_field_if_exists(json_rule, json_to_use, "instructions", str)
- JsonUtils.copy_field_if_exists(json_rule, json_to_use, "enabled", bool, default_value=True)
+ JsonUtils.copy_field_if_exists(json_rule, json_to_use, "enabled", bool,
+ default_value=True)
json_ids = dict()
JsonUtils.convert_name_to_id(json_rule, json_ids, "policy", "policy_id", "policy",
PolicyManager, self._user_id)
- JsonUtils.convert_name_to_id(json_rule, json_to_use, "meta_rule", "meta_rule_id", "meta_rule", ModelManager, self._user_id)
+ JsonUtils.convert_name_to_id(json_rule, json_to_use, "meta_rule", "meta_rule_id",
+ "meta_rule", ModelManager, self._user_id)
json_subject_ids = dict()
json_object_ids = dict()
json_action_ids = dict()
- JsonUtils.convert_names_to_ids(json_rule["rule"], json_subject_ids, "subject_data", "subject", "subject_data", PolicyManager, self._user_id, json_ids["policy_id"])
- JsonUtils.convert_names_to_ids(json_rule["rule"], json_object_ids, "object_data", "object", "object_data", PolicyManager, self._user_id, json_ids["policy_id"])
- JsonUtils.convert_names_to_ids(json_rule["rule"], json_action_ids, "action_data", "action", "action_data", PolicyManager, self._user_id, json_ids["policy_id"])
+ JsonUtils.convert_names_to_ids(json_rule["rule"], json_subject_ids, "subject_data",
+ "subject", "subject_data", PolicyManager, self._user_id,
+ json_ids["policy_id"])
+ JsonUtils.convert_names_to_ids(json_rule["rule"], json_object_ids, "object_data",
+ "object", "object_data", PolicyManager, self._user_id,
+ json_ids["policy_id"])
+ JsonUtils.convert_names_to_ids(json_rule["rule"], json_action_ids, "action_data",
+ "action", "action_data", PolicyManager, self._user_id,
+ json_ids["policy_id"])
meta_rule = ModelManager.get_meta_rules(self._user_id, json_to_use["meta_rule_id"])
meta_rule = [v for v in meta_rule.values()]
meta_rule = meta_rule[0]
- json_to_use_rule = self._reorder_rules_ids(json_rule, meta_rule["subject_categories"], json_subject_ids["subject"], json_ids["policy_id"], PolicyManager.get_subject_data)
- json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(json_rule, meta_rule["object_categories"], json_object_ids["object"], json_ids["policy_id"], PolicyManager.get_object_data)
- json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(json_rule, meta_rule["action_categories"], json_action_ids["action"], json_ids["policy_id"], PolicyManager.get_action_data)
+ json_to_use_rule = self._reorder_rules_ids(json_rule, meta_rule["subject_categories"],
+ json_subject_ids["subject"],
+ json_ids["policy_id"],
+ PolicyManager.get_subject_data)
+ json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(json_rule, meta_rule[
+ "object_categories"], json_object_ids["object"], json_ids["policy_id"],
+ PolicyManager.get_object_data)
+ json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(json_rule, meta_rule[
+ "action_categories"], json_action_ids["action"], json_ids["policy_id"],
+ PolicyManager.get_action_data)
json_to_use["rule"] = json_to_use_rule
try:
logger.debug("Adding / updating a rule from json {}".format(json_to_use))
- PolicyManager.add_rule(self._user_id, json_ids["policy_id"], json_to_use["meta_rule_id"], json_to_use)
+ PolicyManager.add_rule(self._user_id, json_ids["policy_id"],
+ json_to_use["meta_rule_id"], json_to_use)
except exceptions.RuleExisting:
pass
except exceptions.PolicyUnknown:
@@ -136,11 +148,18 @@ class JsonImport(Resource):
json_to_use = dict()
JsonUtils.copy_field_if_exists(json_meta_rule, json_to_use, "name", str)
JsonUtils.copy_field_if_exists(json_meta_rule, json_to_use, "description", str)
- JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "subject_categories", "subject_categories", "subject_category", ModelManager, self._user_id)
- JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "object_categories", "object_categories", "object_category", ModelManager, self._user_id)
- JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "action_categories", "action_categories", "action_category", ModelManager, self._user_id)
+ JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "subject_categories",
+ "subject_categories", "subject_category", ModelManager,
+ self._user_id)
+ JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "object_categories",
+ "object_categories", "object_category", ModelManager,
+ self._user_id)
+ JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "action_categories",
+ "action_categories", "action_category", ModelManager,
+ self._user_id)
logger.debug("Adding / updating a metarule from json {}".format(json_meta_rule))
- meta_rule = ModelManager.add_meta_rule(self._user_id, meta_rule_id=None, value=json_to_use)
+ meta_rule = ModelManager.add_meta_rule(self._user_id, meta_rule_id=None,
+ value=json_to_use)
logger.debug("Added / updated meta rule : {}".format(meta_rule))
def _import_subject_object_action_assignments(self, json_item_assignments, type_element):
@@ -156,29 +175,40 @@ class JsonImport(Resource):
for json_item_assignment in json_item_assignments:
item_override = JsonUtils.get_override(json_item_assignment)
if item_override is True:
- raise ForbiddenOverride("{} assignments do not support override flag !".format(type_element))
+ raise ForbiddenOverride(
+ "{} assignments do not support override flag !".format(type_element))
json_assignment = dict()
- JsonUtils.convert_name_to_id(json_item_assignment, json_assignment, "category", "category_id", type_element + "_category", ModelManager, self._user_id)
+ JsonUtils.convert_name_to_id(json_item_assignment, json_assignment, "category",
+ "category_id", type_element + "_category", ModelManager,
+ self._user_id)
has_found_data = False
# loop over policies
for policy_id in policies:
json_data = dict()
try:
- JsonUtils.convert_name_to_id(json_item_assignment, json_assignment, type_element, "id", type_element, PolicyManager, self._user_id, policy_id)
- JsonUtils.convert_names_to_ids(json_item_assignment, json_data, "assignments", "data_id", type_element + "_data", PolicyManager, self._user_id, policy_id, json_assignment["category_id"])
+ JsonUtils.convert_name_to_id(json_item_assignment, json_assignment,
+ type_element, "id", type_element, PolicyManager,
+ self._user_id, policy_id)
+ JsonUtils.convert_names_to_ids(json_item_assignment, json_data, "assignments",
+ "data_id", type_element + "_data", PolicyManager,
+ self._user_id, policy_id,
+ json_assignment["category_id"])
has_found_data = True
except UnknownName:
# the category or data has not been found in this policy : we look into the next one
continue
for data_id in json_data["data_id"]:
# find the policy related to the current data
- data = get_method(self._user_id, policy_id, data_id, json_assignment["category_id"])
+ data = get_method(self._user_id, policy_id, data_id,
+ json_assignment["category_id"])
if data is not None and len(data) == 1:
- logger.debug("Adding / updating a {} assignment from json {}".format(type_element,
- json_assignment))
- import_method(self._user_id, policy_id, json_assignment["id"], json_assignment["category_id"],
+ logger.debug(
+ "Adding / updating a {} assignment from json {}".format(type_element,
+ json_assignment))
+ import_method(self._user_id, policy_id, json_assignment["id"],
+ json_assignment["category_id"],
data_id)
else:
raise UnknownData("Unknown data with id {}".format(data_id))
@@ -189,7 +219,8 @@ class JsonImport(Resource):
type_element,
json_item_assignment))
- def _import_subject_object_action_datas(self, json_items_data, mandatory_policy_ids, type_element):
+ def _import_subject_object_action_datas(self, json_items_data, mandatory_policy_ids,
+ type_element):
if type_element == "subject":
import_method = getattr(PolicyManager, 'set_' + type_element + '_data')
else:
@@ -202,16 +233,20 @@ class JsonImport(Resource):
for json_item_data in json_items_data:
item_override = JsonUtils.get_override(json_items_data)
if item_override is True:
- raise ForbiddenOverride("{} datas do not support override flag !".format(type_element))
+ raise ForbiddenOverride(
+ "{} datas do not support override flag !".format(type_element))
json_to_use = dict()
JsonUtils.copy_field_if_exists(json_item_data, json_to_use, "name", str)
JsonUtils.copy_field_if_exists(json_item_data, json_to_use, "description", str)
json_policy = dict()
# field_mandatory : not mandatory if there is some mandatory policies
- JsonUtils.convert_names_to_ids(json_item_data, json_policy, "policies", "policy_id", "policy",
- PolicyManager, self._user_id, field_mandatory=len(mandatory_policy_ids) == 0)
+ JsonUtils.convert_names_to_ids(json_item_data, json_policy, "policies", "policy_id",
+ "policy",
+ PolicyManager, self._user_id,
+ field_mandatory=len(mandatory_policy_ids) == 0)
json_category = dict()
- JsonUtils.convert_name_to_id(json_item_data, json_category, "category", "category_id", type_element+"_category",
+ JsonUtils.convert_name_to_id(json_item_data, json_category, "category", "category_id",
+ type_element + "_category",
ModelManager, self._user_id)
policy_ids = []
if "policy_id" in json_policy:
@@ -222,16 +257,20 @@ class JsonImport(Resource):
mandatory_policy_ids.append(policy_id)
if len(mandatory_policy_ids) == 0:
- raise InvalidJson("Invalid data, the policy shall be set when importing {}".format(json_item_data))
+ raise InvalidJson("Invalid data, the policy shall be set when importing {}".format(
+ json_item_data))
category_id = None
if "category_id" in json_category:
category_id = json_category["category_id"]
if category_id is None:
- raise InvalidJson("Invalid data, the category shall be set when importing {}".format(json_item_data))
+ raise InvalidJson(
+ "Invalid data, the category shall be set when importing {}".format(
+ json_item_data))
for policy_id in mandatory_policy_ids:
try:
- data = import_method(self._user_id, policy_id, category_id=category_id, value=json_to_use)
+ data = import_method(self._user_id, policy_id, category_id=category_id,
+ value=json_to_use)
except exceptions.PolicyUnknown:
raise UnknownPolicy("Unknown policy with id {}".format(policy_id))
except Exception as e:
@@ -260,13 +299,16 @@ class JsonImport(Resource):
JsonUtils.copy_field_if_exists(json_item_category, json_to_use, "description", str)
item_override = JsonUtils.get_override(json_item_category)
if item_override is True:
- raise ForbiddenOverride("{} categories do not support override flag !".format(type_element))
+ raise ForbiddenOverride(
+ "{} categories do not support override flag !".format(type_element))
try:
category = import_method(self._user_id, existing_id, json_to_use)
- except (exceptions.SubjectCategoryExisting, exceptions.ObjectCategoryExisting, exceptions.ActionCategoryExisting):
+ except (exceptions.SubjectCategoryExisting, exceptions.ObjectCategoryExisting,
+ exceptions.ActionCategoryExisting):
# it already exists: do nothing
- logger.warning("Ignored {} category with name {} is already in the database".format(type_element, json_to_use["name"]))
+ logger.warning("Ignored {} category with name {} is already in the database".format(
+ type_element, json_to_use["name"]))
except Exception as e:
logger.warning("Error while importing the category : {}".format(str(e)))
logger.exception(str(e))
@@ -284,7 +326,9 @@ class JsonImport(Resource):
JsonUtils.copy_field_if_exists(json_item, json_without_policy_name, "name", str)
JsonUtils.copy_field_if_exists(json_item, json_without_policy_name, "description", str)
JsonUtils.copy_field_if_exists(json_item, json_without_policy_name, "extra", dict)
- JsonUtils.convert_names_to_ids(json_item, json_without_policy_name, "policies", "policy_list", "policy", PolicyManager, self._user_id, field_mandatory=False)
+ JsonUtils.convert_names_to_ids(json_item, json_without_policy_name, "policies",
+ "policy_list", "policy", PolicyManager, self._user_id,
+ field_mandatory=False)
policy_ids = json_without_policy_name["policy_list"]
for mandatory_policy_id in mandatory_policy_ids:
if mandatory_policy_id not in policy_ids:
@@ -297,7 +341,9 @@ class JsonImport(Resource):
raise ForbiddenOverride("{} does not support override flag !".format(type_element))
if len(policy_ids) == 0:
- raise MissingPolicy("a {} needs at least one policy to be created or updated : {}".format(type_element, json.dumps(json_item)))
+ raise MissingPolicy(
+ "a {} needs at least one policy to be created or updated : {}".format(
+ type_element, json.dumps(json_item)))
for policy_id in policy_ids:
try:
@@ -307,7 +353,8 @@ class JsonImport(Resource):
if items_in_db[key_in_db]["name"] == json_without_policy_name["name"]:
key = key_in_db
break
- element = import_method(self._user_id, policy_id, perimeter_id=key, value=json_without_policy_name)
+ element = import_method(self._user_id, policy_id, perimeter_id=key,
+ value=json_without_policy_name)
logger.debug("Added / updated {} : {}".format(type_element, element))
except exceptions.PolicyUnknown:
@@ -344,24 +391,29 @@ class JsonImport(Resource):
if policy_override is False and policy_does_exist:
if policy_id:
policy_mandatory_ids.append(policy_id)
- logger.warning("Existing policy not updated because of the override option is not set !")
+ logger.warning(
+ "Existing policy not updated because of the override option is not set !")
continue
json_without_model_name = dict()
JsonUtils.copy_field_if_exists(json_policy, json_without_model_name, "name", str)
JsonUtils.copy_field_if_exists(json_policy, json_without_model_name, "description", str)
JsonUtils.copy_field_if_exists(json_policy, json_without_model_name, "genre", str)
- JsonUtils.convert_name_to_id(json_policy, json_without_model_name, "model", "model_id", "model", ModelManager, self._user_id, field_mandatory=False)
+ JsonUtils.convert_name_to_id(json_policy, json_without_model_name, "model", "model_id",
+ "model", ModelManager, self._user_id,
+ field_mandatory=False)
if not policy_does_exist:
logger.debug("Creating policy {} ".format(json_without_model_name))
- added_policy = PolicyManager.add_policy(self._user_id, None, json_without_model_name)
+ added_policy = PolicyManager.add_policy(self._user_id, None,
+ json_without_model_name)
if policy_mandatory is True:
keys = list(added_policy.keys())
policy_mandatory_ids.append(keys[0])
elif policy_override is True:
logger.debug("Updating policy {} ".format(json_without_model_name))
- updated_policy = PolicyManager.update_policy(self._user_id, policy_id, json_without_model_name)
+ updated_policy = PolicyManager.update_policy(self._user_id, policy_id,
+ json_without_model_name)
if policy_mandatory is True:
policy_mandatory_ids.append(policy_id)
return policy_mandatory_ids
@@ -376,7 +428,8 @@ class JsonImport(Resource):
model_in_db = None
model_id = None
for model_key in models:
- if ("id" in json_model and model_key == json_model["id"]) or ("name" in json_model and models[model_key]["name"] == json_model["name"]):
+ if ("id" in json_model and model_key == json_model["id"]) or (
+ "name" in json_model and models[model_key]["name"] == json_model["name"]):
model_in_db = models[model_key]
model_id = model_key
@@ -385,7 +438,8 @@ class JsonImport(Resource):
raise UnknownModel("Unknown model ")
json_key = dict()
- JsonUtils.convert_names_to_ids(json_model, json_key, "meta_rules", "meta_rule_id", "meta_rule", ModelManager, self._user_id)
+ JsonUtils.convert_names_to_ids(json_model, json_key, "meta_rules", "meta_rule_id",
+ "meta_rule", ModelManager, self._user_id)
for meta_rule_id in json_key["meta_rule_id"]:
if meta_rule_id not in model_in_db["meta_rules"]:
model_in_db["meta_rules"].append(meta_rule_id)
@@ -410,18 +464,20 @@ class JsonImport(Resource):
model_id = model_key
# end TODO
- JsonUtils.copy_field_if_exists(json_model, json_without_new_metarules, "description", str)
+ JsonUtils.copy_field_if_exists(json_model, json_without_new_metarules, "description",
+ str)
if model_in_db is None:
model_does_exist = False
else:
- json_without_new_metarules["meta_rule_id"] = model_in_db["meta_rules"]
+ json_without_new_metarules["meta_rules"] = model_in_db["meta_rules"]
model_does_exist = True
model_override = JsonUtils.get_override(json_model)
if not model_does_exist:
logger.debug("Creating model {} ".format(json_without_new_metarules))
ModelManager.add_model(self._user_id, None, json_without_new_metarules)
elif model_override is True:
- logger.debug("Updating model with id {} : {} ".format(model_id, json_without_new_metarules))
+ logger.debug(
+ "Updating model with id {} : {} ".format(model_id, json_without_new_metarules))
ModelManager.update_model(self._user_id, model_id, json_without_new_metarules)
def _import_pdps(self, json_pdps):
@@ -477,10 +533,6 @@ class JsonImport(Resource):
if key in json_content:
logger.info("Importing {}...".format(key))
self._import_subject_object_action_categories(json_content[key], in_key)
- key = in_key + "_data"
- if key in json_content:
- logger.info("Importing {}...".format(key))
- self._import_subject_object_action_datas(json_content[key], mandatory_policy_ids, in_key)
# import meta rules
if "meta_rules" in json_content:
@@ -492,6 +544,14 @@ class JsonImport(Resource):
logger.info("Updating models with meta rules...")
self._import_models_with_new_meta_rules(json_content["models"])
+ for elt in list_element:
+ in_key = elt["key"]
+ key = in_key + "_data"
+ if key in json_content:
+ logger.info("Importing {}...".format(key))
+ self._import_subject_object_action_datas(json_content[key], mandatory_policy_ids,
+ in_key)
+
# import subjects assignments, idem for object and action
for elt in list_element:
in_key = elt["key"]
diff --git a/moon_manager/moon_manager/api/json_utils.py b/moon_manager/moon_manager/api/json_utils.py
index cc4c8b0f..6a5830f1 100644
--- a/moon_manager/moon_manager/api/json_utils.py
+++ b/moon_manager/moon_manager/api/json_utils.py
@@ -6,28 +6,24 @@ logger = logging.getLogger("moon.manager.api." + __name__)
class UnknownName(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(UnknownName, self).__init__(message)
class UnknownId(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(UnknownId, self).__init__(message)
class MissingIdOrName(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(MissingIdOrName, self).__init__(message)
class UnknownField(BaseException):
def __init__(self, message):
-
# Call the base class constructor with the parameters it needs
super(UnknownField, self).__init__(message)
@@ -64,7 +60,8 @@ class JsonUtils:
json_out[field_name] = []
@staticmethod
- def _get_element_in_db_from_id(element_type, element_id, user_id, policy_id, category_id, meta_rule_id, manager):
+ def _get_element_in_db_from_id(element_type, element_id, user_id, policy_id, category_id,
+ meta_rule_id, manager):
# the item is supposed to be in the db, we check it exists!
if element_type == "model":
data_db = manager.get_models(user_id, model_id=element_id)
@@ -85,11 +82,14 @@ class JsonUtils:
elif element_type == "meta_rule":
data_db = manager.get_meta_rules(user_id, meta_rule_id=element_id)
elif element_type == "subject_data":
- data_db = manager.get_subject_data(user_id, policy_id, data_id=element_id, category_id=category_id)
+ data_db = manager.get_subject_data(user_id, policy_id, data_id=element_id,
+ category_id=category_id)
elif element_type == "object_data":
- data_db = manager.get_object_data(user_id, policy_id, data_id=element_id, category_id=category_id)
+ data_db = manager.get_object_data(user_id, policy_id, data_id=element_id,
+ category_id=category_id)
elif element_type == "action_data":
- data_db = manager.get_action_data(user_id, policy_id, data_id=element_id, category_id=category_id)
+ data_db = manager.get_action_data(user_id, policy_id, data_id=element_id,
+ category_id=category_id)
elif element_type == "meta_rule":
data_db = manager.get_meta_rules(user_id, meta_rule_id=meta_rule_id)
else:
@@ -101,15 +101,16 @@ class JsonUtils:
if element_type == "subject_data" or element_type == "object_data" or element_type == "action_data":
if data_db is not None and isinstance(data_db, list):
# TODO remove comments after fixing the bug on moondb when adding metarule : we can have several identical entries !
- #if len(data_db) > 1:
+ # if len(data_db) > 1:
# raise Exception("Several {} with the same id : {}".format(element_type, data_db))
data_db = data_db[0]
- if data_db is not None and data_db["data"] is not None and isinstance(data_db["data"], dict):
+ if data_db is not None and data_db["data"] is not None and isinstance(data_db["data"],
+ dict):
# TODO remove comments after fixing the bug on moondb when adding metarule : we can have several identical entries !
- #if len(data_db["data"].values()) != 1:
+ # if len(data_db["data"].values()) != 1:
# raise Exception("Several {} with the same id : {}".format(element_type, data_db))
- #data_db = data_db["data"]
+ # data_db = data_db["data"]
# TODO remove these two lines after fixing the bug on moondb when adding metarule : we can have several identical entries !
list_values = list(data_db["data"].values())
data_db = list_values[0]
@@ -117,7 +118,8 @@ class JsonUtils:
return data_db
@staticmethod
- def _get_element_id_in_db_from_name(element_type, element_name, user_id, policy_id, category_id, meta_rule_id, manager):
+ def _get_element_id_in_db_from_name(element_type, element_name, user_id, policy_id, category_id,
+ meta_rule_id, manager):
if element_type == "model":
data_db = manager.get_models(user_id)
elif element_type == "policy":
@@ -156,7 +158,8 @@ class JsonUtils:
return key_id
else:
for elt in data_db:
- if isinstance(elt, dict) and "data" in elt: # we handle here subject_data, object_data and action_data...
+ if isinstance(elt,
+ dict) and "data" in elt: # we handle here subject_data, object_data and action_data...
for data_key in elt["data"]:
# logger.info("data from the db {} ".format(elt["data"][data_key]))
data = elt["data"][data_key]
@@ -167,20 +170,31 @@ class JsonUtils:
return None
@staticmethod
- def convert_name_to_id(json_in, json_out, field_name_in, field_name_out, element_type, manager, user_id, policy_id=None, category_id=None, meta_rule_id=None, field_mandatory=True):
+ def convert_name_to_id(json_in, json_out, field_name_in, field_name_out, element_type, manager,
+ user_id, policy_id=None, category_id=None, meta_rule_id=None,
+ field_mandatory=True):
if field_name_in not in json_in:
raise UnknownField("The field {} is not in the input json".format(field_name_in))
if "id" in json_in[field_name_in]:
- data_db = JsonUtils._get_element_in_db_from_id(element_type, json_in[field_name_in]["id"], user_id, policy_id, category_id, meta_rule_id, manager)
+ data_db = JsonUtils._get_element_in_db_from_id(element_type,
+ json_in[field_name_in]["id"], user_id,
+ policy_id, category_id, meta_rule_id,
+ manager)
if data_db is None:
- raise UnknownId("No {} with id {} found in database".format(element_type, json_in[field_name_in]["id"]))
+ raise UnknownId("No {} with id {} found in database".format(element_type,
+ json_in[field_name_in]["id"]))
json_out[field_name_out] = json_in[field_name_in]["id"]
elif "name" in json_in[field_name_in]:
- id_in_db = JsonUtils._get_element_id_in_db_from_name(element_type, json_in[field_name_in]["name"], user_id, policy_id, category_id, meta_rule_id, manager)
+ id_in_db = JsonUtils._get_element_id_in_db_from_name(element_type,
+ json_in[field_name_in]["name"],
+ user_id, policy_id, category_id,
+ meta_rule_id, manager)
if id_in_db is None:
- raise UnknownName("No {} with name {} found in database".format(element_type,json_in[field_name_in]["name"]))
+ raise UnknownName(
+ "No {} with name {} found in database".format(element_type,
+ json_in[field_name_in]["name"]))
json_out[field_name_out] = id_in_db
elif field_mandatory is True:
raise MissingIdOrName("No id or name found in the input json {}".format(json_in))
@@ -188,7 +202,9 @@ class JsonUtils:
@staticmethod
def convert_id_to_name(id_, json_out, field_name_out, element_type, manager, user_id,
policy_id=None, category_id=None, meta_rule_id=None):
- json_out[field_name_out] = {"name": JsonUtils.convert_id_to_name_string(id_, element_type, manager, user_id, policy_id, category_id, meta_rule_id)}
+ json_out[field_name_out] = {
+ "name": JsonUtils.convert_id_to_name_string(id_, element_type, manager, user_id,
+ policy_id, category_id, meta_rule_id)}
@staticmethod
def __convert_results_to_element(element):
@@ -203,9 +219,10 @@ class JsonUtils:
@staticmethod
def convert_id_to_name_string(id_, element_type, manager, user_id,
- policy_id=None, category_id=None, meta_rule_id=None):
+ policy_id=None, category_id=None, meta_rule_id=None):
- element = JsonUtils._get_element_in_db_from_id(element_type, id_, user_id, policy_id, category_id, meta_rule_id, manager)
+ element = JsonUtils._get_element_in_db_from_id(element_type, id_, user_id, policy_id,
+ category_id, meta_rule_id, manager)
# logger.info(element)
if element is None:
raise UnknownId("No {} with id {} found in database".format(element_type, id_))
@@ -218,31 +235,42 @@ class JsonUtils:
return None
@staticmethod
- def convert_names_to_ids(json_in, json_out, field_name_in, field_name_out, element_type, manager, user_id, policy_id=None, category_id=None, meta_rule_id=None, field_mandatory=True):
+ def convert_names_to_ids(json_in, json_out, field_name_in, field_name_out, element_type,
+ manager, user_id, policy_id=None, category_id=None, meta_rule_id=None,
+ field_mandatory=True):
ids = []
if field_name_in not in json_in:
raise UnknownField("The field {} is not in the input json".format(field_name_in))
for elt in json_in[field_name_in]:
if "id" in elt:
- data_db = JsonUtils._get_element_in_db_from_id(element_type, elt["id"], user_id, policy_id, category_id, meta_rule_id, manager)
+ data_db = JsonUtils._get_element_in_db_from_id(element_type, elt["id"], user_id,
+ policy_id, category_id,
+ meta_rule_id, manager)
if data_db is None:
- raise UnknownId("No {} with id {} found in database".format(element_type, elt["id"]))
+ raise UnknownId(
+ "No {} with id {} found in database".format(element_type, elt["id"]))
ids.append(elt["id"])
elif "name" in elt:
- id_in_db = JsonUtils._get_element_id_in_db_from_name(element_type, elt["name"], user_id, policy_id, category_id, meta_rule_id, manager)
+ id_in_db = JsonUtils._get_element_id_in_db_from_name(element_type, elt["name"],
+ user_id, policy_id,
+ category_id, meta_rule_id,
+ manager)
if id_in_db is None:
- raise UnknownName("No {} with name {} found in database".format(element_type, elt["name"]))
+ raise UnknownName(
+ "No {} with name {} found in database".format(element_type, elt["name"]))
ids.append(id_in_db)
elif field_mandatory is True:
raise MissingIdOrName("No id or name found in the input json {}".format(elt))
json_out[field_name_out] = ids
@staticmethod
- def convert_ids_to_names(ids, json_out, field_name_out, element_type, manager, user_id, policy_id=None, category_id=None, meta_rule_id=None):
+ def convert_ids_to_names(ids, json_out, field_name_out, element_type, manager, user_id,
+ policy_id=None, category_id=None, meta_rule_id=None):
res_array = []
for id_ in ids:
- element = JsonUtils._get_element_in_db_from_id(element_type, id_, user_id, policy_id, category_id, meta_rule_id, manager)
+ element = JsonUtils._get_element_in_db_from_id(element_type, id_, user_id, policy_id,
+ category_id, meta_rule_id, manager)
if element is None:
raise UnknownId("No {} with id {} found in database".format(element_type, id_))
res = JsonUtils.__convert_results_to_element(element)
@@ -252,4 +280,3 @@ class JsonUtils:
if "value" in res and "name" in res["value"]:
res_array.append({"name": res["value"]["name"]})
json_out[field_name_out] = res_array
-
diff --git a/moon_manager/moon_manager/api/meta_data.py b/moon_manager/moon_manager/api/meta_data.py
index 62ca050f..b0b86d10 100644
--- a/moon_manager/moon_manager/api/meta_data.py
+++ b/moon_manager/moon_manager/api/meta_data.py
@@ -30,7 +30,7 @@ class SubjectCategories(Resource):
"/subject_categories/<string:category_id>",
)
- @validate_input("get",kwargs_state=[False,False])
+ @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
@@ -50,7 +50,7 @@ class SubjectCategories(Resource):
return {"subject_categories": data}
- @validate_input("post",body_state={"name":True})
+ @validate_input("post", body_state={"name": True})
@check_auth
def post(self, category_id=None, user_id=None):
"""Create or update a subject category.
@@ -74,7 +74,7 @@ class SubjectCategories(Resource):
return {"subject_categories": data}
- @validate_input("delete",kwargs_state=[True,False])
+ @validate_input("delete", kwargs_state=[True, False])
@check_auth
def delete(self, category_id=None, user_id=None):
"""Delete a subject category
@@ -105,7 +105,7 @@ class ObjectCategories(Resource):
"/object_categories/<string:category_id>",
)
- @validate_input("get",kwargs_state=[False,False])
+ @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
@@ -125,7 +125,7 @@ class ObjectCategories(Resource):
return {"object_categories": data}
- @validate_input("post", body_state={"name":True})
+ @validate_input("post", body_state={"name": True})
@check_auth
def post(self, category_id=None, user_id=None):
"""Create or update a object category.
@@ -202,7 +202,7 @@ class ActionCategories(Resource):
return {"action_categories": data}
- @validate_input("post", body_state={"name":True})
+ @validate_input("post", body_state={"name": True})
@check_auth
def post(self, category_id=None, user_id=None):
"""Create or update an action category.
diff --git a/moon_manager/moon_manager/api/meta_rules.py b/moon_manager/moon_manager/api/meta_rules.py
index 3dc9996b..738aad71 100644
--- a/moon_manager/moon_manager/api/meta_rules.py
+++ b/moon_manager/moon_manager/api/meta_rules.py
@@ -57,7 +57,8 @@ class MetaRules(Resource):
return {"meta_rules": data}
- @validate_input("post", body_state={"name":True, "subject_categories":True, "object_categories":True, "action_categories":True})
+ @validate_input("post", body_state={"name": True, "subject_categories": False,
+ "object_categories": False, "action_categories": False})
@check_auth
def post(self, meta_rule_id=None, user_id=None):
"""Add a meta rule
@@ -90,7 +91,9 @@ class MetaRules(Resource):
return {"meta_rules": data}
- @validate_input("patch", kwargs_state=[True, False], body_state={"name":True, "subject_categories":True, "object_categories":True, "action_categories":True})
+ @validate_input("patch", kwargs_state=[True, False],
+ body_state={"name": True, "subject_categories": False,
+ "object_categories": False, "action_categories": False})
@check_auth
def patch(self, meta_rule_id=None, user_id=None):
"""Update a meta rule
@@ -117,7 +120,7 @@ class MetaRules(Resource):
}
:internal_api: set_meta_rules
"""
- data = ModelManager.set_meta_rule(
+ data = ModelManager.update_meta_rule(
user_id=user_id, meta_rule_id=meta_rule_id, value=request.json)
return {"meta_rules": data}
@@ -147,4 +150,3 @@ class MetaRules(Resource):
user_id=user_id, meta_rule_id=meta_rule_id)
return {"result": True}
-
diff --git a/moon_manager/moon_manager/api/models.py b/moon_manager/moon_manager/api/models.py
index c3068367..c72396cf 100644
--- a/moon_manager/moon_manager/api/models.py
+++ b/moon_manager/moon_manager/api/models.py
@@ -50,7 +50,7 @@ class Models(Resource):
return {"models": data}
- @validate_input("post", body_state={"name":True, "meta_rules":True})
+ @validate_input("post", body_state={"name": True, "meta_rules": False})
@check_auth
def post(self, uuid=None, user_id=None):
"""Create model.
@@ -94,7 +94,8 @@ class Models(Resource):
return {"result": True}
- @validate_input("patch", kwargs_state=[True, False], body_state={"name":True, "meta_rules":True})
+ @validate_input("patch", kwargs_state=[True, False],
+ body_state={"name": True, "meta_rules": False})
@check_auth
def patch(self, uuid=None, user_id=None):
"""Update a model
@@ -114,4 +115,3 @@ class Models(Resource):
user_id=user_id, model_id=uuid, value=request.json)
return {"models": data}
-
diff --git a/moon_manager/moon_manager/api/pdp.py b/moon_manager/moon_manager/api/pdp.py
index a5d7c007..65a6a5f1 100644
--- a/moon_manager/moon_manager/api/pdp.py
+++ b/moon_manager/moon_manager/api/pdp.py
@@ -42,9 +42,11 @@ def delete_pod(uuid):
for pod_value in pod_list:
if "pdp_id" in pod_value:
if pod_value["pdp_id"] == uuid:
- req = requests.delete("{}://{}:{}/pods/{}".format(proto, hostname, port, pod_key))
+ req = requests.delete(
+ "{}://{}:{}/pods/{}".format(proto, hostname, port, pod_key))
if req.status_code != 200:
- logger.warning("Cannot delete pod {} - {}".format(pod_key, pod_value['name']))
+ logger.warning(
+ "Cannot delete pod {} - {}".format(pod_key, pod_value['name']))
logger.debug(req.content)
# Note (Asteroide): no need to go further if one match
break
@@ -119,7 +121,8 @@ class PDP(Resource):
return {"pdps": data}
- @validate_input("post", body_state={"name": True, "security_pipeline": True, "keystone_project_id": True})
+ @validate_input("post", body_state={"name": True, "security_pipeline": True,
+ "keystone_project_id": True})
@check_auth
def post(self, uuid=None, user_id=None):
"""Create pdp.
@@ -176,7 +179,9 @@ class PDP(Resource):
return {"result": True}
- @validate_input("patch", kwargs_state=[True, False], body_state={"name": True, "security_pipeline": True, "keystone_project_id": True})
+ @validate_input("patch", kwargs_state=[True, False],
+ body_state={"name": True, "security_pipeline": True,
+ "keystone_project_id": True})
@check_auth
def patch(self, uuid, user_id=None):
"""Update a pdp
@@ -207,4 +212,3 @@ class PDP(Resource):
add_pod(uuid=uuid, data=data[uuid])
return {"pdps": data}
-
diff --git a/moon_manager/moon_manager/api/perimeter.py b/moon_manager/moon_manager/api/perimeter.py
index 6c39c43d..a0fda4ad 100644
--- a/moon_manager/moon_manager/api/perimeter.py
+++ b/moon_manager/moon_manager/api/perimeter.py
@@ -17,7 +17,6 @@ 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"
logger = logging.getLogger("moon.manager.api." + __name__)
@@ -64,9 +63,9 @@ class Subjects(Resource):
return {"subjects": data}
- @validate_input("post", body_state={"name":True})
+ @validate_input("post", body_state={"name": True})
@check_auth
- def post(self, uuid, perimeter_id=None, user_id=None):
+ def post(self, uuid=None, perimeter_id=None, user_id=None):
"""Create or update a subject.
:param uuid: uuid of the policy
@@ -90,23 +89,15 @@ class Subjects(Resource):
:internal_api: set_subject
"""
- if not perimeter_id:
- data = PolicyManager.get_subjects(user_id=user_id,
- policy_id=uuid)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
data = PolicyManager.add_subject(
user_id=user_id, policy_id=uuid,
perimeter_id=perimeter_id, value=request.json)
return {"subjects": data}
- @validate_input("patch", kwargs_state=[False, True, False], body_state={"name":True})
+ @validate_input("patch", kwargs_state=[False, True, False])
@check_auth
- def patch(self, uuid, perimeter_id=None, user_id=None):
+ def patch(self, uuid=None, perimeter_id=None, user_id=None):
"""Create or update a subject.
:param uuid: uuid of the policy
@@ -129,19 +120,8 @@ class Subjects(Resource):
}
:internal_api: set_subject
"""
-
- if not perimeter_id:
- data = PolicyManager.get_subjects(user_id=user_id,
- policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_subject(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
-
+ data = PolicyManager.update_subject(user_id=user_id, perimeter_id=perimeter_id,
+ value=request.json)
return {"subjects": data}
@validate_input("delete", kwargs_state=[False, True, False])
@@ -210,9 +190,9 @@ class Objects(Resource):
return {"objects": data}
- @validate_input("post", body_state={"name":True})
+ @validate_input("post", body_state={"name": True})
@check_auth
- def post(self, uuid, perimeter_id=None, user_id=None):
+ def post(self, uuid=None, perimeter_id=None, user_id=None):
"""Create or update a object.
:param uuid: uuid of the policy
@@ -230,22 +210,15 @@ class Objects(Resource):
}
:internal_api: set_object
"""
-
- data = PolicyManager.get_objects(user_id=user_id, policy_id=uuid)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
data = PolicyManager.add_object(
user_id=user_id, policy_id=uuid,
perimeter_id=perimeter_id, value=request.json)
return {"objects": data}
- @validate_input("patch", kwargs_state=[False, True, False], body_state={"name":True})
+ @validate_input("patch", kwargs_state=[False, True, False])
@check_auth
- def patch(self, uuid, perimeter_id=None, user_id=None):
+ def patch(self, uuid=None, perimeter_id=None, user_id=None):
"""Create or update a object.
:param uuid: uuid of the policy
@@ -263,16 +236,8 @@ class Objects(Resource):
}
:internal_api: set_object
"""
-
- data = PolicyManager.get_objects(user_id=user_id, policy_id=uuid)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_object(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
+ data = PolicyManager.update_object(user_id=user_id, perimeter_id=perimeter_id,
+ value=request.json)
return {"objects": data}
@@ -336,9 +301,9 @@ class Actions(Resource):
return {"actions": data}
- @validate_input("post", body_state={"name":True})
+ @validate_input("post", body_state={"name": True})
@check_auth
- def post(self, uuid, perimeter_id=None, user_id=None):
+ def post(self, uuid=None, perimeter_id=None, user_id=None):
"""Create or update a action.
:param uuid: uuid of the policy
@@ -356,22 +321,15 @@ class Actions(Resource):
}
:internal_api: set_action
"""
-
- data = PolicyManager.get_actions(user_id=user_id, policy_id=uuid)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
data = PolicyManager.add_action(
user_id=user_id, policy_id=uuid,
perimeter_id=perimeter_id, value=request.json)
return {"actions": data}
- @validate_input("patch", kwargs_state=[False, True, False], body_state={"name":True})
+ @validate_input("patch", kwargs_state=[False, True, False])
@check_auth
- def patch(self, uuid, perimeter_id=None, user_id=None):
+ def patch(self, uuid=None, perimeter_id=None, user_id=None):
"""Create or update a action.
:param uuid: uuid of the policy
@@ -389,16 +347,8 @@ class Actions(Resource):
}
:internal_api: set_action
"""
-
- data = PolicyManager.get_actions(user_id=user_id, policy_id=uuid)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_action(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
+ data = PolicyManager.update_action(user_id=user_id, perimeter_id=perimeter_id,
+ value=request.json)
return {"actions": data}
diff --git a/moon_manager/moon_manager/api/policies.py b/moon_manager/moon_manager/api/policies.py
index 9fe237b2..3264e8e0 100644
--- a/moon_manager/moon_manager/api/policies.py
+++ b/moon_manager/moon_manager/api/policies.py
@@ -14,7 +14,6 @@ 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"
logger = logging.getLogger("moon.manager.api." + __name__)
@@ -54,7 +53,7 @@ class Policies(Resource):
return {"policies": data}
- @validate_input("post", body_state={"name": True, "model_id":True})
+ @validate_input("post", body_state={"name": True, "model_id": False})
@check_auth
def post(self, uuid=None, user_id=None):
"""Create policy.
@@ -83,7 +82,7 @@ class Policies(Resource):
return {"policies": data}
- @validate_input("delete", kwargs_state=[ True, False])
+ @validate_input("delete", kwargs_state=[True, False])
@check_auth
def delete(self, uuid=None, user_id=None):
"""Delete a policy
@@ -101,7 +100,8 @@ class Policies(Resource):
return {"result": True}
- @validate_input("patch", kwargs_state=[True, False], body_state={"name": True, "model_id":True})
+ @validate_input("patch", kwargs_state=[True, False],
+ body_state={"name": True, "model_id": False})
@check_auth
def patch(self, uuid=None, user_id=None):
"""Update a policy
@@ -123,4 +123,3 @@ class Policies(Resource):
user_id=user_id, policy_id=uuid, value=request.json)
return {"policies": data}
-
diff --git a/moon_manager/moon_manager/api/rules.py b/moon_manager/moon_manager/api/rules.py
index a0248097..cbd39969 100644
--- a/moon_manager/moon_manager/api/rules.py
+++ b/moon_manager/moon_manager/api/rules.py
@@ -51,12 +51,13 @@ class Rules(Resource):
"""
data = PolicyManager.get_rules(user_id=user_id,
- policy_id=uuid,
- rule_id=rule_id)
+ policy_id=uuid,
+ rule_id=rule_id)
return {"rules": data}
- @validate_input("post", kwargs_state=[True, False, False], body_state={"meta_rule_id": True, "rule": True, "instructions": True})
+ @validate_input("post", kwargs_state=[True, False, False],
+ body_state={"meta_rule_id": True, "rule": True, "instructions": True})
@check_auth
def post(self, uuid=None, rule_id=None, user_id=None):
"""Add a rule to a meta rule
@@ -132,4 +133,3 @@ class Rules(Resource):
user_id=user_id, policy_id=uuid, rule_id=rule_id)
return {"result": True}
-
diff --git a/moon_manager/moon_manager/api/slaves.py b/moon_manager/moon_manager/api/slaves.py
index 769b681f..e2928de0 100644
--- a/moon_manager/moon_manager/api/slaves.py
+++ b/moon_manager/moon_manager/api/slaves.py
@@ -16,7 +16,6 @@ from python_moonutilities.security_functions import check_auth
from python_moonutilities import configuration
from python_moonutilities.security_functions import validate_input
-
__version__ = "4.3.0"
logger = logging.getLogger("moon.manager.api." + __name__)
@@ -84,11 +83,11 @@ class Slaves(Resource):
"""
logger.info("Will made a request for {}".format(uuid))
if request.json.get("op") == "replace" \
- and request.json.get("variable") == "configured" \
+ and request.json.get("variable") == "configured" \
and request.json.get("value"):
req = requests.post("http://{}:{}/pods".format(
self.orchestrator_hostname, self.orchestrator_port,
- ),
+ ),
json={"slave_name": uuid}
)
if req.status_code != 200:
@@ -97,7 +96,7 @@ class Slaves(Resource):
))
return "Orchestrator: " + str(req.reason), req.status_code
elif request.json.get("op") == "replace" \
- and request.json.get("variable") == "configured" \
+ and request.json.get("variable") == "configured" \
and not request.json.get("value"):
req = requests.delete("http://{}:{}/pods/{}".format(
self.orchestrator_hostname, self.orchestrator_port, uuid
diff --git a/moon_manager/moon_manager/http_server.py b/moon_manager/moon_manager/http_server.py
index 204e7e04..53879529 100644
--- a/moon_manager/moon_manager/http_server.py
+++ b/moon_manager/moon_manager/http_server.py
@@ -26,7 +26,6 @@ from moon_manager.api.json_export import JsonExport
from python_moonutilities import configuration
from python_moondb.core import PDPManager
-
logger = logging.getLogger("moon.manager.http_server")
__API__ = (
@@ -36,7 +35,7 @@ __API__ = (
SubjectAssignments, ObjectAssignments, ActionAssignments,
SubjectData, ObjectData, ActionData,
Models, Policies, PDP, Slaves, JsonImport, JsonExport
- )
+)
class Server:
@@ -87,7 +86,7 @@ class Root(Resource):
"""
The root of the web service
"""
- __urls__ = ("/", )
+ __urls__ = ("/",)
__methods = ("get", "post", "put", "delete", "options")
def get(self):
@@ -112,7 +111,8 @@ class CustomApi(Api):
@staticmethod
def handle_error(e):
try:
- error_message = dumps({"result": False, 'message': str(e), "code": getattr(e, "code", 500)})
+ error_message = dumps(
+ {"result": False, 'message': str(e), "code": getattr(e, "code", 500)})
logger.error(e, exc_info=True)
logger.error(error_message)
return make_response(error_message, getattr(e, "code", 500))
diff --git a/moon_manager/moon_manager/server.py b/moon_manager/moon_manager/server.py
index a8db8fd5..70ddaee0 100644
--- a/moon_manager/moon_manager/server.py
+++ b/moon_manager/moon_manager/server.py
@@ -7,7 +7,6 @@ import logging
from python_moonutilities import configuration, exceptions
from moon_manager.http_server import HTTPServer
-
logger = logging.getLogger("moon.manager.server")
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 12cb208e..2ee2627d 100644
--- a/moon_manager/tests/unit_python/api/import_export_utilities.py
+++ b/moon_manager/tests/unit_python/api/import_export_utilities.py
@@ -9,7 +9,7 @@ import api.test_perimeter as test_perimeter
import api.test_meta_data as test_categories
import api.test_data as test_data
import api.test_meta_rules as test_meta_rules
-import api.test_assignemnt as test_assignments
+import api.test_assignement as test_assignments
import api.test_rules as test_rules
import logging
@@ -38,7 +38,6 @@ def clean_subjects(client):
logger.info("subjects policy_keys {}".format(policy_keys))
for policy_key in policy_keys:
client.delete("/policies/{}/subjects/{}".format(policy_key, key))
- client.delete("/subjects/{}".format(key))
def clean_objects(client):
@@ -50,11 +49,11 @@ def clean_objects(client):
logger.info("objects policy_keys {}".format(policy_keys))
for policy_key in policy_keys:
client.delete("/policies/{}/objects/{}".format(policy_key, key))
- client.delete("/objects/{}".format(key))
def clean_actions(client):
actions = test_perimeter.get_actions(client)
+ actions = test_perimeter.get_actions(client)
logger.info("actions {}".format(actions))
for key in actions[1]["actions"]:
action = actions[1]["actions"][key]
@@ -62,7 +61,6 @@ def clean_actions(client):
logger.info("action policy_keys {}".format(policy_keys))
for policy_key in policy_keys:
client.delete("/policies/{}/actions/{}".format(policy_key, key))
- client.delete("/actions/{}".format(key))
def clean_subject_categories(client):
@@ -92,25 +90,33 @@ def clean_subject_data(client):
for policy_key in policies["policies"]:
req, data = test_data.get_subject_data(client, policy_id=policy_key)
logger.info("============= data {}".format(data))
- for key in data["subject_data"]:
- logger.info("============= Deleting {}/{}".format(policy_key, key))
- client.delete("/policies/{}/subject_data/{}".format(policy_key, key))
+ for data_item in data["subject_data"]:
+ if data_item["data"]:
+ for data_id in data_item["data"]:
+ logger.info("============= Deleting {}/{}".format(policy_key, data_id))
+ client.delete("/policies/{}/subject_data/{}/{}".format(policy_key, data_item['category_id'], data_id))
def clean_object_data(client):
req, policies = test_policies.get_policies(client)
for policy_key in policies["policies"]:
req, data = test_data.get_object_data(client, policy_id=policy_key)
- for key in data["object_data"]:
- client.delete("/policies/{}/object_data/{}".format(policy_key, key))
+ for data_item in data["object_data"]:
+ if data_item["data"]:
+ for data_id in data_item["data"]:
+ logger.info("============= object_data {}/{}".format(policy_key, data_id))
+ client.delete("/policies/{}/object_data/{}/{}".format(policy_key, data_item['category_id'], data_id))
def clean_action_data(client):
req, policies = test_policies.get_policies(client)
for policy_key in policies["policies"]:
req, data = test_data.get_action_data(client, policy_id=policy_key)
- for key in data["action_data"]:
- client.delete("/policies/{}/action_data/{}".format(policy_key, key))
+ for data_item in data["action_data"]:
+ if data_item["data"]:
+ for data_id in data_item["data"]:
+ logger.info("============= action_data {}/{}".format(policy_key, data_id))
+ client.delete("/policies/{}/action_data/{}/{}".format(policy_key, data_item['category_id'], data_id))
def clean_meta_rule(client):
@@ -165,10 +171,9 @@ def clean_rules(client):
req, policies = test_policies.get_policies(client)
for policy_key in policies["policies"]:
req, rules = test_rules.get_rules(client, policy_key)
- rules = rules["rules"]
- rules = rules["rules"]
+ rules = rules["rules"]["rules"]
for rule_key in rules:
- client.delete("/policies/{}/rules/{}".format(policy_key, rule_key))
+ req = client.delete("/policies/{}/rules/{}".format(policy_key, rule_key["id"]))
def clean_all(client):
@@ -178,7 +183,6 @@ def clean_all(client):
clean_object_assignments(client)
clean_action_assignments(client)
- clean_meta_rule(client)
clean_subject_data(client)
clean_object_data(client)
@@ -192,5 +196,7 @@ def clean_all(client):
clean_object_categories(client)
clean_action_categories(client)
+
clean_policies(client)
clean_models(client)
+ clean_meta_rule(client) \ No newline at end of file
diff --git a/moon_manager/tests/unit_python/api/test_assignement.py b/moon_manager/tests/unit_python/api/test_assignement.py
new file mode 100644
index 00000000..b56fb420
--- /dev/null
+++ b/moon_manager/tests/unit_python/api/test_assignement.py
@@ -0,0 +1,280 @@
+import api.utilities as utilities
+import json
+from helpers import data_builder as builder
+from uuid import uuid4
+
+
+# subject_categories_test
+
+
+def get_subject_assignment(client, policy_id):
+ req = client.get("/policies/{}/subject_assignments".format(policy_id))
+ subject_assignment = utilities.get_json(req.data)
+ return req, subject_assignment
+
+
+def add_subject_assignment(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ subject_id = builder.create_subject(policy_id)
+ data_id = builder.create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+
+ data = {
+ "id": subject_id,
+ "category_id": subject_category_id,
+ "data_id": data_id
+ }
+ 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 add_subject_assignment_without_cat_id(client):
+
+ data = {
+ "id": "subject_id",
+ "category_id": "",
+ "data_id": "data_id"
+ }
+ req = client.post("/policies/{}/subject_assignments".format("1111"), 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, sub_id, cat_id,data_id):
+ req = client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_id, sub_id, cat_id,data_id))
+ return req
+
+
+def test_add_subject_assignment():
+ client = utilities.register_client()
+ req, subject_assignment = add_subject_assignment(client)
+ assert req.status_code == 200
+ assert isinstance(subject_assignment, dict)
+ assert "subject_assignments" in subject_assignment
+
+
+# def test_add_subject_assignment_without_cat_id():
+# client = utilities.register_client()
+# req, subject_assignment = add_subject_assignment_without_cat_id(client)
+# assert req.status_code == 400
+# assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]"
+
+
+def test_get_subject_assignment():
+ client = utilities.register_client()
+ policy_id = builder.get_policy_id_with_subject_assignment()
+ req, subject_assignment = get_subject_assignment(client, policy_id)
+ assert req.status_code == 200
+ assert isinstance(subject_assignment, dict)
+ assert "subject_assignments" in subject_assignment
+
+
+def test_delete_subject_assignment():
+ client = utilities.register_client()
+ policy_id = builder.get_policy_id_with_subject_assignment()
+ 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 == 404
+
+
+# ---------------------------------------------------------------------------
+# object_categories_test
+
+
+def get_object_assignment(client, policy_id):
+ req = client.get("/policies/{}/object_assignments".format(policy_id))
+ object_assignment = utilities.get_json(req.data)
+ return req, object_assignment
+
+
+def add_object_assignment(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ object_id = builder.create_object(policy_id)
+ data_id = builder.create_object_data(policy_id=policy_id, category_id=object_category_id)
+
+ data = {
+ "id": object_id,
+ "category_id": object_category_id,
+ "data_id": data_id
+ }
+
+ req = client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ object_assignment = utilities.get_json(req.data)
+ return req, object_assignment
+
+
+def add_object_assignment_without_cat_id(client):
+
+ data = {
+ "id": "object_id",
+ "category_id": "",
+ "data_id": "data_id"
+ }
+ req = client.post("/policies/{}/object_assignments".format("1111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ object_assignment = utilities.get_json(req.data)
+ return req, object_assignment
+
+
+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
+
+
+def test_get_object_assignment():
+ policy_id = builder.get_policy_id_with_object_assignment()
+ client = utilities.register_client()
+ req, object_assignment = get_object_assignment(client, policy_id)
+ assert req.status_code == 200
+ assert isinstance(object_assignment, dict)
+ assert "object_assignments" in object_assignment
+
+
+def test_add_object_assignment():
+ client = utilities.register_client()
+ req, object_assignment = add_object_assignment(client)
+ assert req.status_code == 200
+ assert "object_assignments" in object_assignment
+
+
+# def test_add_object_assignment_without_cat_id():
+# client = utilities.register_client()
+# req, object_assignment = add_object_assignment_without_cat_id(client)
+# assert req.status_code == 400
+# assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]"
+
+
+def test_delete_object_assignment():
+ client = utilities.register_client()
+ policy_id = builder.get_policy_id_with_object_assignment()
+ 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 == 404
+
+
+# ---------------------------------------------------------------------------
+# action_categories_test
+
+
+def get_action_assignment(client, policy_id):
+ req = client.get("/policies/{}/action_assignments".format(policy_id))
+ action_assignment = utilities.get_json(req.data)
+ return req, action_assignment
+
+
+def add_action_assignment(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ action_id = builder.create_action(policy_id)
+ data_id = builder.create_action_data(policy_id=policy_id, category_id=action_category_id)
+
+ data = {
+ "id": action_id,
+ "category_id": action_category_id,
+ "data_id": data_id
+ }
+ req = client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ action_assignment = utilities.get_json(req.data)
+ return req, action_assignment
+
+
+def add_action_assignment_without_cat_id(client):
+
+ data = {
+ "id": "action_id",
+ "category_id": "",
+ "data_id": "data_id"
+ }
+ req = client.post("/policies/{}/action_assignments".format("1111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ action_assignment = utilities.get_json(req.data)
+ return req, action_assignment
+
+
+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
+
+
+def test_get_action_assignment():
+ policy_id = builder.get_policy_id_with_action_assignment()
+ client = utilities.register_client()
+ req, action_assignment = get_action_assignment(client, policy_id)
+ assert req.status_code == 200
+ assert isinstance(action_assignment, dict)
+ assert "action_assignments" in action_assignment
+
+
+def test_add_action_assignment():
+ client = utilities.register_client()
+ req, action_assignment = add_action_assignment(client)
+ assert req.status_code == 200
+ assert "action_assignments" in action_assignment
+
+
+# def test_add_action_assignment_without_cat_id():
+# client = utilities.register_client()
+# req, action_assignment = add_action_assignment_without_cat_id(client)
+# assert req.status_code == 400
+# assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]"
+
+
+def test_delete_action_assignment():
+ client = utilities.register_client()
+ policy_id = builder.get_policy_id_with_action_assignment()
+ 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
+
+
+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 == 404
+
+# ---------------------------------------------------------------------------
diff --git a/moon_manager/tests/unit_python/api/test_data.py b/moon_manager/tests/unit_python/api/test_data.py
index ff0856af..433f69e6 100644
--- a/moon_manager/tests/unit_python/api/test_data.py
+++ b/moon_manager/tests/unit_python/api/test_data.py
@@ -36,8 +36,8 @@ def add_subject_data(client, name):
return req, subject_data
-def delete_subject_data(client, policy_id):
- req = client.delete("/policies/{}/subject_data".format(policy_id))
+def delete_subject_data(client, policy_id, category_id, data_id):
+ req = client.delete("/policies/{}/subject_data/{}/{}".format(policy_id,category_id,data_id))
return req
@@ -65,31 +65,24 @@ def test_add_subject_data():
def test_delete_subject_data():
client = utilities.register_client()
subject_category_id, object_category_id, action_category_id, meta_rule_id,policy_id = builder.create_new_policy()
- success_req = delete_subject_data(client, policy_id)
+ data_id = builder.create_subject_data(policy_id,subject_category_id)
+ success_req = delete_subject_data(client, policy_id, subject_category_id, data_id )
assert success_req.status_code == 200
-def test_add_subject_data_with_empty_user():
+def test_add_subject_data_with_forbidden_char_in_user():
client = utilities.register_client()
- req, subject_data = add_subject_data(client, "")
+ req, subject_data = add_subject_data(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
-
-
-def test_add_subject_data_with_user_contain_space():
- client = utilities.register_client()
- req, subject_data = add_subject_data(client, "test user")
- assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_delete_subject_data_without_policy_id():
client = utilities.register_client()
- success_req = delete_subject_data(client, "")
+ success_req = delete_subject_data(client, "", "", "")
assert success_req.status_code == 404
# ---------------------------------------------------------------------------
-
# object_categories_test
@@ -118,8 +111,8 @@ def add_object_data(client, name):
return req, object_data
-def delete_object_data(client, policy_id):
- req = client.delete("/policies/{}/object_data".format(policy_id))
+def delete_object_data(client, policy_id, category_id, data_id):
+ req = client.delete("/policies/{}/object_data/{}/{}".format(policy_id, category_id, data_id))
return req
@@ -139,42 +132,34 @@ def test_add_object_data():
assert isinstance(object_data, dict)
value = object_data["object_data"]['data']
assert "object_data" in object_data
- id = list(value.keys())[0]
- print("-----------------------")
- print(id)
- print(value[id])
- print("-----------------------")
- assert value[id]['name'] == "testuser"
- assert value[id]['description'] == "description of {}".format("testuser")
+ _id = list(value.keys())[0]
+ assert value[_id]['name'] == "testuser"
+ assert value[_id]['description'] == "description of {}".format("testuser")
def test_delete_object_data():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
- success_req = delete_object_data(client, policy_id)
- assert success_req.status_code == 200
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy()
+ data_id = builder.create_object_data(policy_id, object_category_id)
-def test_add_object_data_with_empty_user():
- client = utilities.register_client()
- req, subject_data = add_object_data(client, "")
- assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ success_req = delete_object_data(client, policy_id, data_id, object_category_id)
+ assert success_req.status_code == 200
-def test_add_object_data_with_user_contain_space():
+def test_add_object_data_with_forbidden_char_in_user():
client = utilities.register_client()
- req, object_data = add_object_data(client, "test user")
+ req, subject_data = add_object_data(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_delete_object_data_without_policy_id():
client = utilities.register_client()
- success_req = delete_object_data(client, "")
+ success_req = delete_object_data(client, "", "", "")
assert success_req.status_code == 404
-# ---------------------------------------------------------------------------
+# ---------------------------------------------------------------------------
# action_categories_test
@@ -203,8 +188,8 @@ def add_action_data(client, name):
return req, action_data
-def delete_action_data(client, policy_id):
- req = client.delete("/policies/{}/action_data".format(policy_id))
+def delete_action_data(client, policy_id, categorgy_id, data_id):
+ req = client.delete("/policies/{}/action_data/{}/{}".format(policy_id, categorgy_id, data_id))
return req
@@ -231,27 +216,24 @@ def test_add_action_data():
def test_delete_action_data():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
- success_req = delete_action_data(client, policy_id)
- assert success_req.status_code == 200
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy()
+ data_id = builder.create_action_data(policy_id, action_category_id)
-def test_add_action_data_with_empty_user():
- client = utilities.register_client()
- req, action_data = add_action_data(client, "")
- assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ success_req = delete_action_data(client, policy_id, data_id, action_category_id)
+
+ assert success_req.status_code == 200
-def test_add_action_data_with_user_contain_space():
+def test_add_action_data_with_forbidden_char_in_user():
client = utilities.register_client()
- req, action_data = add_action_data(client, "test user")
+ req, action_data = add_action_data(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_delete_action_data_without_policy_id():
client = utilities.register_client()
- success_req = delete_action_data(client, "")
+ success_req = delete_action_data(client, "", "", "")
assert success_req.status_code == 404
# ---------------------------------------------------------------------------
diff --git a/moon_manager/tests/unit_python/api/test_import.py b/moon_manager/tests/unit_python/api/test_import.py
index f1ab8251..af5f753a 100644
--- a/moon_manager/tests/unit_python/api/test_import.py
+++ b/moon_manager/tests/unit_python/api/test_import.py
@@ -9,7 +9,7 @@ import api.test_policies as test_policies
import api.test_meta_data as test_categories
import api.test_data as test_data
import api.test_meta_rules as test_meta_rules
-import api.test_assignemnt as test_assignments
+import api.test_assignement as test_assignments
import api.test_rules as test_rules
import api.import_export_utilities as import_export_utilities
@@ -42,7 +42,8 @@ OBJECTS = [
"objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
{"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}],
"objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
- {"objects": [{"name": "test object", "description": "new description of the object", "extra": {"test": "test extra"},
+ {"objects": [{"name": "test object", "description": "new description of the object",
+ "extra": {"test": "test extra"},
"policies": [{"name": "test other policy"}]}]},
{"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}],
"objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": [{"name": "test policy"}]}]},
@@ -225,7 +226,14 @@ def test_import_subject_object_action():
if counter == 2 or counter == 4:
clean_method(client)
- req = client.post("/import", content_type='application/json', data=json.dumps(element))
+
+ if counter == 3:
+ req = client.patch("/{}s/{}".format(type_element,perimeter_id), content_type='application/json',
+ data=json.dumps(
+ element["{}s".format(type_element)][0]))
+ else :
+ req = client.post("/import", content_type='application/json',
+ data=json.dumps(element))
if counter < 2:
assert req.status_code == 500
continue
@@ -237,10 +245,13 @@ def test_import_subject_object_action():
#assert counter < 2 #  this is an expected failure
#continue
- assert data == "Import ok !"
+ if counter != 3:
+ assert data == "Import ok !"
get_elements = utilities.get_json(client.get("/"+type_element + "s").data)
get_elements = get_elements[type_element + "s"]
+ perimeter_id = list(get_elements.keys())[0]
+
assert len(list(get_elements.keys())) == 1
values = list(get_elements.values())
assert values[0]["name"] == name
@@ -338,6 +349,7 @@ def test_import_meta_rules():
def test_import_subject_object_action_assignments():
client = utilities.register_client()
import_export_utilities.clean_all(client)
+
req = client.post("/import", content_type='application/json', data=json.dumps(PRE_ASSIGNMENTS))
data = utilities.get_json(req.data)
assert data == "Import ok !"
diff --git a/moon_manager/tests/unit_python/api/test_meta_data.py b/moon_manager/tests/unit_python/api/test_meta_data.py
index 4cb86913..e6cb0833 100644
--- a/moon_manager/tests/unit_python/api/test_meta_data.py
+++ b/moon_manager/tests/unit_python/api/test_meta_data.py
@@ -1,7 +1,10 @@
import json
import api.utilities as utilities
+from helpers import data_builder
+from uuid import uuid4
-#subject_categories_test
+
+# subject_categories_test
def get_subject_categories(client):
@@ -52,18 +55,35 @@ def test_add_subject_categories():
assert value['description'] == "description of {}".format("testuser")
-def test_add_subject_categories_with_empty_user():
+def test_add_subject_categories_with_existed_name():
+ client = utilities.register_client()
+ name = uuid4().hex
+ req, subject_categories = add_subject_categories(client, name)
+ assert req.status_code == 200
+ req, subject_categories = add_subject_categories(client, name)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Subject Category Existing'
+
+
+def test_add_subject_categories_name_contain_space():
+ client = utilities.register_client()
+ req, subject_categories = add_subject_categories(client, " ")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Category Name Invalid'
+
+
+def test_add_subject_categories_with_empty_name():
client = utilities.register_client()
- req, subject_categories = add_subject_categories(client, "")
+ req, subject_categories = add_subject_categories(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
-def test_add_subject_categories_with_user_contain_space():
+def test_add_subject_categories_with_name_contain_space():
client = utilities.register_client()
- req, subject_categories = add_subject_categories(client, "test user")
+ req, subject_categories = add_subject_categories(client, "test<z>user")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_delete_subject_categories():
@@ -79,8 +99,8 @@ def test_delete_subject_categories_without_id():
assert json.loads(req.data)["message"] == "400: Subject Category Unknown"
-#---------------------------------------------------------------------------
-#object_categories_test
+# ---------------------------------------------------------------------------
+# object_categories_test
def get_object_categories(client):
req = client.get("/object_categories")
@@ -130,18 +150,35 @@ def test_add_object_categories():
assert value['description'] == "description of {}".format("testuser")
-def test_add_object_categories_with_empty_user():
+def test_add_object_categories_with_existed_name():
+ client = utilities.register_client()
+ name = uuid4().hex
+ req, object_categories = add_object_categories(client, name)
+ assert req.status_code == 200
+ req, object_categories = add_object_categories(client, name)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Object Category Existing'
+
+
+def test_add_object_categories_name_contain_space():
+ client = utilities.register_client()
+ req, subject_categories = add_object_categories(client, " ")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Category Name Invalid'
+
+
+def test_add_object_categories_with_empty_name():
client = utilities.register_client()
- req, object_categories = add_object_categories(client, "")
+ req, object_categories = add_object_categories(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
-def test_add_object_categories_with_user_contain_space():
+def test_add_object_categories_with_name_contain_space():
client = utilities.register_client()
- req, object_categories = add_object_categories(client, "test user")
+ req, object_categories = add_object_categories(client, "test<a>user")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_delete_object_categories():
@@ -157,8 +194,8 @@ def test_delete_object_categories_without_id():
assert json.loads(req.data)["message"] == "400: Object Category Unknown"
-#---------------------------------------------------------------------------
-#action_categories_test
+# ---------------------------------------------------------------------------
+# action_categories_test
def get_action_categories(client):
req = client.get("/action_categories")
@@ -208,18 +245,35 @@ def test_add_action_categories():
assert value['description'] == "description of {}".format("testuser")
-def test_add_action_categories_with_empty_user():
+def test_add_action_categories_with_existed_name():
client = utilities.register_client()
- req, action_categories = add_action_categories(client, "")
+ name = uuid4().hex
+ req, action_categories = add_action_categories(client, name)
+ assert req.status_code == 200
+ req, action_categories = add_action_categories(client, name)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Action Category Existing'
+
+
+def test_add_action_categories_name_contain_space():
+ client = utilities.register_client()
+ req, subject_categories = add_action_categories(client, " ")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Category Name Invalid'
+
+
+def test_add_action_categories_with_empty_name():
+ client = utilities.register_client()
+ req, action_categories = add_action_categories(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
-def test_add_action_categories_with_user_contain_space():
+def test_add_action_categories_with_name_contain_space():
client = utilities.register_client()
- req, action_categories = add_action_categories(client, "test user")
+ req, action_categories = add_action_categories(client, "test<a>user")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_delete_action_categories():
@@ -233,3 +287,19 @@ def test_delete_action_categories_without_id():
req = delete_action_categories_without_id(client)
assert req.status_code == 400
assert json.loads(req.data)["message"] == "400: Action Category Unknown"
+
+
+def test_delete_data_categories_connected_to_meta_rule():
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule()
+ client = utilities.register_client()
+ req = client.delete("/subject_categories/{}".format(subject_category_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Subject Category With Meta Rule Error'
+
+ req = client.delete("/object_categories/{}".format(object_category_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Object Category With Meta Rule Error'
+
+ req = client.delete("/action_categories/{}".format(action_category_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Action Category With Meta Rule Error'
diff --git a/moon_manager/tests/unit_python/api/test_meta_rules.py b/moon_manager/tests/unit_python/api/test_meta_rules.py
index 80d648b4..634f19da 100644
--- a/moon_manager/tests/unit_python/api/test_meta_rules.py
+++ b/moon_manager/tests/unit_python/api/test_meta_rules.py
@@ -1,6 +1,7 @@
import json
import api.utilities as utilities
from helpers import category_helper
+from helpers import data_builder
from uuid import uuid4
@@ -10,32 +11,36 @@ def get_meta_rules(client):
return req, meta_rules
-def add_meta_rules(client, name):
- subject_category = category_helper.add_subject_category(value={"name": "subject category name"+uuid4().hex, "description": "description 1"})
- subject_category_id = list(subject_category.keys())[0]
- object_category = category_helper.add_object_category(value={"name": "object category name"+ uuid4().hex, "description": "description 1"})
- object_category_id = list(object_category.keys())[0]
- action_category = category_helper.add_action_category(value={"name": "action category name"+uuid4().hex, "description": "description 1"})
- action_category_id = list(action_category.keys())[0]
-
- data = {
- "name": name,
- "subject_categories": [subject_category_id],
- "object_categories": [object_category_id],
- "action_categories": [action_category_id]
- }
+def add_meta_rules(client, name, data=None):
+ if not data:
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name" + uuid4().hex, "description": "description 1"})
+ subject_category_id = list(subject_category.keys())[0]
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name" + uuid4().hex, "description": "description 1"})
+ object_category_id = list(object_category.keys())[0]
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name" + uuid4().hex, "description": "description 1"})
+ action_category_id = list(action_category.keys())[0]
+
+ data = {
+ "name": name,
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
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 add_meta_rules_without_subject_category_ids(client, name):
+def add_meta_rules_without_category_ids(client, name):
data = {
- "name": name,
+ "name": name + uuid4().hex,
"subject_categories": [],
- "object_categories": ["object_category_id1"],
- "action_categories": ["action_category_id1"]
+ "object_categories": [],
+ "action_categories": []
}
req = client.post("/meta_rules", data=json.dumps(data),
headers={'Content-Type': 'application/json'})
@@ -43,37 +48,45 @@ def add_meta_rules_without_subject_category_ids(client, name):
return req, meta_rules
-def update_meta_rules(client, name, metaRuleId):
- subject_category = category_helper.add_subject_category(
- value={"name": "subject category name update" + uuid4().hex, "description": "description 1"})
- subject_category_id = list(subject_category.keys())[0]
- object_category = category_helper.add_object_category(
- value={"name": "object category name update" + uuid4().hex, "description": "description 1"})
- object_category_id = list(object_category.keys())[0]
- action_category = category_helper.add_action_category(
- value={"name": "action category name update" + uuid4().hex, "description": "description 1"})
- action_category_id = list(action_category.keys())[0]
- data = {
- "name": name,
- "subject_categories": [subject_category_id],
- "object_categories": [object_category_id],
- "action_categories": [action_category_id]
- }
+def update_meta_rules(client, name, metaRuleId, data=None):
+ if not data:
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name update" + uuid4().hex,
+ "description": "description 1"})
+ subject_category_id = list(subject_category.keys())[0]
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name update" + uuid4().hex,
+ "description": "description 1"})
+ object_category_id = list(object_category.keys())[0]
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name update" + uuid4().hex,
+ "description": "description 1"})
+ action_category_id = list(action_category.keys())[0]
+ data = {
+ "name": name,
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+
req = client.patch("/meta_rules/{}".format(metaRuleId), data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
+ 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'})
+def update_meta_rules_with_categories(client, name, data=None, meta_rule_id=None):
+ if not meta_rule_id:
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule()
+ data = {
+ "name": name,
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+
+ req = client.patch("/meta_rules/{}".format(meta_rule_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
meta_rules = utilities.get_json(req.data)
return req, meta_rules
@@ -82,9 +95,7 @@ def delete_meta_rules(client, name):
request, meta_rules = get_meta_rules(client)
for key, value in meta_rules['meta_rules'].items():
if value['name'] == name:
- req = client.delete("/meta_rules/{}".format(key))
- break
- return req
+ return client.delete("/meta_rules/{}".format(key))
def delete_meta_rules_without_id(client):
@@ -102,38 +113,143 @@ def test_get_meta_rules():
def test_add_meta_rules():
client = utilities.register_client()
- req, meta_rules = add_meta_rules(client, "testuser")
+ meta_rule_name = uuid4().hex
+ req, meta_rules = add_meta_rules(client, meta_rule_name)
assert req.status_code == 200
assert isinstance(meta_rules, dict)
value = list(meta_rules["meta_rules"].values())[0]
assert "meta_rules" in meta_rules
- assert value['name'] == "testuser"
+ assert value['name'] == meta_rule_name
-def test_add_meta_rules_with_empty_user():
+def test_add_two_meta_rules_with_same_categories_combination():
client = utilities.register_client()
- req, meta_rules = add_meta_rules(client, "")
+ meta_rule_name = uuid4().hex
+ req, meta_rules = add_meta_rules(client, meta_rule_name)
+ assert req.status_code == 200
+ for meta_rule_id in meta_rules['meta_rules']:
+ if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name:
+ data = meta_rules['meta_rules'][meta_rule_id]
+
+ data['name'] = uuid4().hex
+ req, meta_rules = add_meta_rules(client, name=data['name'], data=data)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Meta Rule Existing'
+
+
+def test_add_three_meta_rules_with_different_combination_but_similar_items():
+ client = utilities.register_client()
+ meta_rule_name1 = uuid4().hex
+ req, meta_rules = add_meta_rules(client, meta_rule_name1)
+ assert req.status_code == 200
+ for meta_rule_id in meta_rules['meta_rules']:
+ if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name1:
+ data = meta_rules['meta_rules'][meta_rule_id]
+ break
+
+ meta_rule_name2 = uuid4().hex
+
+ req, meta_rules = add_meta_rules(client, meta_rule_name2)
+
+ for meta_rule_id in meta_rules['meta_rules']:
+ if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name2:
+ data['subject_categories'] += meta_rules['meta_rules'][meta_rule_id][
+ 'subject_categories']
+ data['object_categories'] += meta_rules['meta_rules'][meta_rule_id]['object_categories']
+ data['action_categories'] += meta_rules['meta_rules'][meta_rule_id]['action_categories']
+ break
+
+ data['name'] = uuid4().hex
+
+ req, meta_rules = add_meta_rules(client, name=data['name'], data=data)
+ assert req.status_code == 200
+
+
+def test_add_two_meta_rules_with_different_combination_but_similar_items():
+ client = utilities.register_client()
+ meta_rule_name1 = uuid4().hex
+ meta_rule_name2 = uuid4().hex
+
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name" + uuid4().hex, "description": "description 1"})
+ subject_category_id1 = list(subject_category.keys())[0]
+
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name" + uuid4().hex, "description": "description 1"})
+ object_category_id1 = list(object_category.keys())[0]
+
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name" + uuid4().hex, "description": "description 1"})
+ action_category_id1 = list(action_category.keys())[0]
+
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name" + uuid4().hex, "description": "description 1"})
+ subject_category_id2 = list(subject_category.keys())[0]
+
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name" + uuid4().hex, "description": "description 1"})
+ object_category_id2 = list(object_category.keys())[0]
+
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name" + uuid4().hex, "description": "description 1"})
+ action_category_id2 = list(action_category.keys())[0]
+
+ data = {
+ "name": meta_rule_name1,
+ "subject_categories": [subject_category_id1, subject_category_id2],
+ "object_categories": [object_category_id1, object_category_id2],
+ "action_categories": [action_category_id1, action_category_id2]
+ }
+ req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data)
+ assert req.status_code == 200
+ data = {
+ "name": meta_rule_name2,
+ "subject_categories": [subject_category_id2],
+ "object_categories": [object_category_id1],
+ "action_categories": [action_category_id2]
+ }
+
+ req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data)
+ assert req.status_code == 200
+
+
+def test_add_meta_rule_with_existing_name_error():
+ client = utilities.register_client()
+ name = uuid4().hex
+ req, meta_rules = add_meta_rules(client, name)
+ assert req.status_code == 200
+ req, meta_rules = add_meta_rules(client, name)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Meta Rule Existing'
+
+
+def test_add_meta_rules_with_forbidden_char_in_name():
+ client = utilities.register_client()
+ req, meta_rules = add_meta_rules(client, "<a>")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
-def test_add_meta_rules_with_user_contain_space():
+def test_add_meta_rules_with_blank_name():
client = utilities.register_client()
- req, meta_rules = add_meta_rules(client, "test user")
+ req, meta_rules = add_meta_rules(client, "")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == '400: Meta Rule Error'
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 == 400
- assert json.loads(req.data)["message"] == "Key: 'subject_categories', [Empty Container]"
+ name_meta_rule = uuid4().hex
+ req, meta_rules = add_meta_rules_without_category_ids(client, name_meta_rule)
+ assert req.status_code == 200
def test_delete_meta_rules():
client = utilities.register_client()
- req = delete_meta_rules(client, "testuser")
+ name_meta_rule = uuid4().hex
+ req, meta_rules = add_meta_rules_without_category_ids(client, name_meta_rule)
+ meta_rule_id = next(iter(meta_rules['meta_rules']))
+ req = delete_meta_rules(client, meta_rules['meta_rules'][meta_rule_id]['name'])
assert req.status_code == 200
@@ -154,6 +270,70 @@ def test_update_meta_rules():
get_meta_rules(client)
+def test_update_meta_rule_with_combination_existed():
+ client = utilities.register_client()
+ meta_rule_name1 = uuid4().hex
+ req, meta_rules = add_meta_rules(client, meta_rule_name1)
+ meta_rule_id1 = next(iter(meta_rules['meta_rules']))
+ data1 = meta_rules['meta_rules'][meta_rule_id1]
+
+ meta_rule_name2 = uuid4().hex
+ req, meta_rules = add_meta_rules(client, meta_rule_name2)
+ meta_rule_id2 = next(iter(meta_rules['meta_rules']))
+ data2 = meta_rules['meta_rules'][meta_rule_id2]
+ data1['name'] = data2['name']
+ req_update = update_meta_rules(client, name=meta_rule_name2, metaRuleId=meta_rule_id2,
+ data=data1)
+ assert req_update[0].status_code == 409
+ assert req_update[1]['message']== '409: Meta Rule Existing'
+
+
+def test_update_meta_rule_with_different_combination_but_same_data():
+ client = utilities.register_client()
+ meta_rule_name1 = uuid4().hex
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name" + uuid4().hex, "description": "description 1"})
+ subject_category_id1 = list(subject_category.keys())[0]
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name" + uuid4().hex, "description": "description 1"})
+ object_category_id1 = list(object_category.keys())[0]
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name" + uuid4().hex, "description": "description 1"})
+ action_category_id1 = list(action_category.keys())[0]
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name" + uuid4().hex, "description": "description 1"})
+ subject_category_id2 = list(subject_category.keys())[0]
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name" + uuid4().hex, "description": "description 1"})
+ object_category_id2 = list(object_category.keys())[0]
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name" + uuid4().hex, "description": "description 1"})
+ action_category_id2 = list(action_category.keys())[0]
+
+ data = {
+ "name": meta_rule_name1,
+ "subject_categories": [subject_category_id1, subject_category_id2],
+ "object_categories": [object_category_id1, object_category_id2],
+ "action_categories": [action_category_id1, action_category_id2]
+ }
+ req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data)
+ assert req.status_code == 200
+
+ meta_rule_name2 = uuid4().hex
+ req, meta_rules = add_meta_rules(client, meta_rule_name2)
+ meta_rule_id2 = next(iter(meta_rules['meta_rules']))
+ data2 = {
+ "name": meta_rule_name2,
+ "subject_categories": [subject_category_id1, subject_category_id2],
+ "object_categories": [object_category_id1],
+ "action_categories": [action_category_id1,action_category_id2]
+ }
+
+ req_update = update_meta_rules(client, name=meta_rule_name2, metaRuleId=meta_rule_id2,
+ data=data2)
+ assert req_update[0].status_code == 200
+
+
def test_update_meta_rules_without_id():
client = utilities.register_client()
req_update = update_meta_rules(client, "testuser", "")
@@ -161,15 +341,75 @@ def test_update_meta_rules_without_id():
assert json.loads(req_update[0].data)["message"] == "400: Meta Rule Unknown"
-def test_update_meta_rules_without_user():
+def test_update_meta_rules_without_name():
client = utilities.register_client()
- req_update = update_meta_rules(client, "", "")
+ req_update = update_meta_rules(client, "<br/>", "1234567")
assert req_update[0].status_code == 400
- assert json.loads(req_update[0].data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req_update[0].data)[
+ "message"] == "Key: 'name', [Forbidden characters in string]"
+
+
+def test_update_meta_rules_without_categories():
+ client = utilities.register_client()
+ req_update = update_meta_rules_with_categories(client, "testuser")
+ assert req_update[0].status_code == 200
-def test_update_meta_rules_without_subject_categories():
+def test_update_meta_rules_with_empty_categories():
client = utilities.register_client()
- req_update = update_meta_rules_without_subject_category_ids(client, "testuser")
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule()
+ data = {
+ "name": "testuser",
+ "subject_categories": [""],
+ "object_categories": [""],
+ "action_categories": [""]
+ }
+ req_update = update_meta_rules_with_categories(client, "testuser", data=data,
+ meta_rule_id=meta_rule_id)
+ assert req_update[0].status_code == 400
+ assert req_update[1]['message'] == '400: Subject Category Unknown'
+
+
+def test_update_meta_rules_with_empty_action_category():
+ client = utilities.register_client()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule()
+ data = {
+ "name": "testuser",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [""]
+ }
+ req_update = update_meta_rules_with_categories(client, "testuser", data=data,
+ meta_rule_id=meta_rule_id)
+ assert req_update[0].status_code == 400
+ assert req_update[1]['message'] == '400: Action Category Unknown'
+
+
+def test_update_meta_rules_with_empty_object_category():
+ client = utilities.register_client()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule()
+ data = {
+ "name": "testuser",
+ "subject_categories": [subject_category_id],
+ "object_categories": [""],
+ "action_categories": [action_category_id]
+ }
+ req_update = update_meta_rules_with_categories(client, "testuser", data=data,
+ meta_rule_id=meta_rule_id)
+ assert req_update[0].status_code == 400
+ assert req_update[1]['message'] == '400: Object Category Unknown'
+
+
+def test_update_meta_rules_with_categories_and_one_empty():
+ client = utilities.register_client()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule()
+ data = {
+ "name": "testuser",
+ "subject_categories": [subject_category_id, ""],
+ "object_categories": [object_category_id, ""],
+ "action_categories": [action_category_id, ""]
+ }
+ req_update = update_meta_rules_with_categories(client, "testuser", data=data,
+ meta_rule_id=meta_rule_id)
assert req_update[0].status_code == 400
- assert json.loads(req_update[0].data)["message"] == "Key: 'subject_categories', [Empty Container]"
+ assert req_update[1]['message'] == '400: Subject Category Unknown'
diff --git a/moon_manager/tests/unit_python/api/test_pdp.py b/moon_manager/tests/unit_python/api/test_pdp.py
index 1ac9b84f..53a87b21 100644
--- a/moon_manager/tests/unit_python/api/test_pdp.py
+++ b/moon_manager/tests/unit_python/api/test_pdp.py
@@ -69,16 +69,18 @@ def test_add_pdp():
def test_delete_pdp():
client = utilities.register_client()
request, pdp = get_pdp(client)
+ success_req = None
for key, value in pdp['pdps'].items():
if value['name'] == "testuser":
success_req = delete_pdp(client, key)
break
+ assert success_req
assert success_req.status_code == 200
-def test_add_pdp_with_empty_user():
+def test_add_pdp_with_forbidden_char_in_user():
data = {
- "name": "",
+ "name": "<a>",
"security_pipeline": ["policy_id_1", "policy_id_2"],
"keystone_project_id": "keystone_project_id",
"description": "description of testuser"
@@ -86,46 +88,20 @@ def test_add_pdp_with_empty_user():
client = utilities.register_client()
req, models = add_pdp(client, data)
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [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 == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [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 == 400
- assert json.loads(req.data)["message"] == "Key: 'security_pipeline', [Empty Container]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
-def test_add_pdp_without_keystone():
+def test_add_pdp_with_forbidden_char_in_keystone():
data = {
"name": "testuser",
"security_pipeline": ["policy_id_1", "policy_id_2"],
- "keystone_project_id": "",
+ "keystone_project_id": "<a>",
"description": "description of testuser"
}
client = utilities.register_client()
req, meta_rules = add_pdp(client, data)
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'keystone_project_id', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'keystone_project_id', [Forbidden characters in string]"
def test_update_pdp():
@@ -183,19 +159,6 @@ def test_update_pdp_without_user():
"description": "description of testuser"
}
client = utilities.register_client()
- req_update = update_pdp(client, data, "")
- assert req_update[0].status_code == 400
- assert json.loads(req_update[0].data)["message"] == "Key: 'name', [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, "")
+ req_update = update_pdp(client, data, "<a>")
assert req_update[0].status_code == 400
- assert json.loads(req_update[0].data)["message"] == "Key: 'security_pipeline', [Empty Container]" \ No newline at end of file
+ assert json.loads(req_update[0].data)["message"] == "Forbidden characters in string"
diff --git a/moon_manager/tests/unit_python/api/test_perimeter.py b/moon_manager/tests/unit_python/api/test_perimeter.py
index 322d90c6..ff7b09d7 100644
--- a/moon_manager/tests/unit_python/api/test_perimeter.py
+++ b/moon_manager/tests/unit_python/api/test_perimeter.py
@@ -3,6 +3,7 @@
import json
import api.utilities as utilities
from helpers import data_builder as builder
+import helpers.policy_helper as policy_helper
from uuid import uuid4
@@ -12,33 +13,27 @@ def get_subjects(client):
return req, subjects
-def add_subjects(client, name):
- subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
- subject_category_name="subject_category1" + uuid4().hex,
- object_category_name="object_category1" + uuid4().hex,
- action_category_name="action_category1" + uuid4().hex,
- meta_rule_name="meta_rule_1" + uuid4().hex,
- model_name="model1" + uuid4().hex)
- data = {
- "name": name + uuid4().hex,
- "description": "description of {}".format(name),
- "password": "password for {}".format(name),
- "email": "{}@moon".format(name)
- }
- req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
+def add_subjects(client, policy_id, name, perimeter_id=None, data=None):
+ if not data:
+ name = name + uuid4().hex
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ if not perimeter_id:
+ req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ else:
+ req = client.post("/policies/{}/subjects/{}".format(policy_id, perimeter_id),
+ data=json.dumps(
+ data),
+ headers={'Content-Type': 'application/json'})
subjects = utilities.get_json(req.data)
return req, subjects
-def delete_subject(client):
- subjects = get_subjects(client)
- value = subjects[1]['subjects']
- id = list(value.keys())[0]
- policy_id = builder.get_policy_id_with_subject_assignment()
- return client.delete("/policies/{}/subjects/{}".format(policy_id, id))
-
-
def delete_subjects_without_perimeter_id(client):
req = client.delete("/subjects/{}".format(""))
return req
@@ -54,18 +49,166 @@ def test_perimeter_get_subject():
def test_perimeter_add_subject():
client = utilities.register_client()
- req, subjects = add_subjects(client, "testuser")
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+
+ req, subjects = add_subjects(client, policy_id, "testuser")
value = list(subjects["subjects"].values())[0]
assert req.status_code == 200
- assert "subjects" in subjects
- assert value["name"] is not None
- assert value["email"] is not None
+ assert value["name"]
+ assert value["email"]
+
+
+def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id():
+ client = utilities.register_client()
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ name = "testuser"
+ perimeter_id = uuid4().hex
+ data = {
+ "name": name + uuid4().hex,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ add_subjects(client, policy_id1, data['name'], perimeter_id=perimeter_id, data=data)
+ policies2 = policy_helper.add_policies()
+ policy_id2 = list(policies2.keys())[0]
+ req, subjects = add_subjects(client, policy_id2, data['name'],
+ perimeter_id=perimeter_id, data=data)
+ value = list(subjects["subjects"].values())[0]
+ assert req.status_code == 200
+ assert value["name"]
+ assert value["email"]
+ assert len(value['policy_list']) == 2
+ assert policy_id1 in value['policy_list']
+ assert policy_id2 in value['policy_list']
+
+
+def test_perimeter_add_same_subject_perimeter_id_with_different_name():
+ client = utilities.register_client()
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ perimeter_id = uuid4().hex
+ add_subjects(client, policy_id1, "testuser", perimeter_id=perimeter_id)
+ policies2 = policy_helper.add_policies()
+ policy_id2 = list(policies2.keys())[0]
+ req, subjects = add_subjects(client, policy_id2, "testuser", perimeter_id=perimeter_id)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.'
+
+
+def test_perimeter_add_same_subject_name_with_new_policy_id():
+ client = utilities.register_client()
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ perimeter_id = uuid4().hex
+ name = "testuser" + uuid4().hex
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ req, subjects = add_subjects(client, policy_id1, None, perimeter_id=perimeter_id,
+ data=data)
+ policies2 = policy_helper.add_policies()
+ policy_id2 = list(policies2.keys())[0]
+ value = list(subjects["subjects"].values())[0]
+ data = {
+ "name": value['name'],
+ "description": "description of {}".format(value['name']),
+ "password": "password for {}".format(value['name']),
+ "email": "{}@moon".format(value['name'])
+ }
+ req, subjects = add_subjects(client, policy_id2, None, data=data)
+ value = list(subjects["subjects"].values())[0]
+ assert req.status_code == 200
+ assert value["name"]
+ assert value["email"]
+ assert len(value['policy_list']) == 2
+ assert policy_id1 in value['policy_list']
+ assert policy_id2 in value['policy_list']
+
+
+def test_perimeter_add_same_subject_name_with_same_policy_id():
+ client = utilities.register_client()
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ perimeter_id = uuid4().hex
+ name = "testuser" + uuid4().hex
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ req, subjects = add_subjects(client, policy_id1, None, perimeter_id=perimeter_id,
+ data=data)
+ value = list(subjects["subjects"].values())[0]
+ data = {
+ "name": value['name'],
+ "description": "description of {}".format(value['name']),
+ "password": "password for {}".format(value['name']),
+ "email": "{}@moon".format(value['name'])
+ }
+ req, subjects = add_subjects(client, policy_id1, None, data=data)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_perimeter_add_same_subject_perimeter_id_with_existed_policy_id_in_list():
+ client = utilities.register_client()
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ name = "testuser" + uuid4().hex
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ req, subjects = add_subjects(client, policy_id, name, data=data)
+ perimeter_id = list(subjects["subjects"].values())[0]['id']
+ req, subjects = add_subjects(client, policy_id, name, perimeter_id=perimeter_id, data=data)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_perimeter_add_subject_invalid_policy_id():
+ client = utilities.register_client()
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ name = "testuser"
+ data = {
+ "name": name + uuid4().hex,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ req, subjects = add_subjects(client, policy_id + "0", "testuser", data)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
+
+
+def test_perimeter_add_subject_policy_id_none():
+ client = utilities.register_client()
+ name = "testuser"
+ data = {
+ "name": name + uuid4().hex,
+ "description": "description of {}".format(name),
+ "password": "password for {}".format(name),
+ "email": "{}@moon".format(name)
+ }
+ req, subjects = add_subjects(client, None, "testuser", data)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
-def test_perimeter_add_subject_without_name():
+def test_perimeter_add_subject_with_forbidden_char_in_name():
client = utilities.register_client()
data = {
- "name": "",
+ "name": "<a>",
"description": "description of {}".format(""),
"password": "password for {}".format(""),
"email": "{}@moon".format("")
@@ -73,26 +216,121 @@ def test_perimeter_add_subject_without_name():
req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
-def test_perimeter_add_subject_with_name_contain_spaces():
+def test_perimeter_update_subject_name():
client = utilities.register_client()
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ req, subjects = add_subjects(client, policy_id, "testuser")
+ value1 = list(subjects["subjects"].values())[0]
+ perimeter_id = value1['id']
data = {
- "name": "test user",
- "description": "description of {}".format("test user"),
- "password": "password for {}".format("test user"),
- "email": "{}@moon".format("test user")
+ 'name': value1['name'] + "update"
}
- req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
+ req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subjects = utilities.get_json(req.data)
+ value2 = list(subjects["subjects"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] + 'update' == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] == value2['description']
+
+
+def test_perimeter_update_subject_description():
+ client = utilities.register_client()
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ req, subjects = add_subjects(client, policy_id, "testuser")
+ value1 = list(subjects["subjects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'description': value1['description'] + "update",
+ }
+ req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subjects = utilities.get_json(req.data)
+ value2 = list(subjects["subjects"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] + 'update' == value2['description']
+
+
+def test_perimeter_update_subject_description_and_name():
+ client = utilities.register_client()
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+
+ req, subjects = add_subjects(client, policy_id, "testuser")
+ value1 = list(subjects["subjects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'description': value1['description'] + "update",
+ 'name': value1['name'] + "update"
+ }
+ req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subjects = utilities.get_json(req.data)
+ value2 = list(subjects["subjects"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] + 'update' == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] + 'update' == value2['description']
+
+
+def test_perimeter_update_subject_wrong_id():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, subjects = add_subjects(client, policy_id=policy_id1, name='testuser', data=data)
+ value1 = list(subjects["subjects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update",
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/subjects/{}".format(perimeter_id + "wrong"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.'
+
+
+def test_perimeter_update_subject_name_with_existed_one():
+ client = utilities.register_client()
+ name1 = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ perimeter_id1 = uuid4().hex
+ req, subjects = add_subjects(client, policy_id=policy_id1, name=name1,
+ perimeter_id=perimeter_id1)
+ value1 = list(subjects["subjects"].values())[0]
+ perimeter_id2 = uuid4().hex
+ name2 = 'testuser' + uuid4().hex
+ req, subjects = add_subjects(client, policy_id=policy_id1, name=name2,
+ perimeter_id=perimeter_id2)
+ data = {
+ 'name': value1['name'],
+ }
+ req = client.patch("/subjects/{}".format(perimeter_id2), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 409
def test_perimeter_delete_subject():
client = utilities.register_client()
- req = delete_subject(client)
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ req, subjects = add_subjects(client, policy_id, "testuser")
+ subject_id = list(subjects["subjects"].values())[0]["id"]
+ req = client.delete("/policies/{}/subjects/{}".format(policy_id, subject_id))
assert req.status_code == 200
@@ -109,31 +347,30 @@ def get_objects(client):
return req, objects
-def add_objects(client, name):
- subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy(
- subject_category_name="subject_category1" + uuid4().hex,
- object_category_name="object_category1" + uuid4().hex,
- action_category_name="action_category1" + uuid4().hex,
- meta_rule_name="meta_rule_1" + uuid4().hex,
- model_name="model1" + uuid4().hex)
- data = {
- "name": name + uuid4().hex,
- "description": "description of {}".format(name),
- }
- req = client.post("/policies/{}/objects/".format(policyId), data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
+def add_objects(client, name, policyId=None, data=None, perimeter_id=None):
+ if not policyId:
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
+ if not data:
+ data = {
+ "name": name + uuid4().hex,
+ "description": "description of {}".format(name),
+ }
+ if not perimeter_id:
+ req = client.post("/policies/{}/objects/".format(policyId), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ else:
+ req = client.post("/policies/{}/objects/{}".format(policyId, perimeter_id),
+ data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
objects = utilities.get_json(req.data)
return req, objects
-def delete_object(client):
- objects = get_objects(client)
- value = objects[1]['objects']
- id = list(value.keys())[0]
- policy_id = builder.get_policy_id_with_object_assignment()
- return client.delete("/policies/{}/objects/{}".format(policy_id, id))
-
-
def delete_objects_without_perimeter_id(client):
req = client.delete("/objects/{}".format(""))
return req
@@ -152,37 +389,279 @@ def test_perimeter_add_object():
req, objects = add_objects(client, "testuser")
value = list(objects["objects"].values())[0]
assert req.status_code == 200
- assert "objects" in objects
- assert value['name'] is not None
+ assert value['name']
+
+
+def test_perimeter_add_object_with_wrong_policy_id():
+ client = utilities.register_client()
+ req, objects = add_objects(client, "testuser", policyId='wrong')
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
+
+
+def test_perimeter_add_object_with_policy_id_none():
+ client = utilities.register_client()
+ data = {
+ "name": "testuser" + uuid4().hex,
+ "description": "description of {}".format("testuser"),
+ }
+ req = client.post("/policies/{}/objects/".format(None), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
+
+
+def test_perimeter_add_same_object_name_with_new_policy_id():
+ client = utilities.register_client()
+ req, objects = add_objects(client, "testuser")
+ value1 = list(objects["objects"].values())[0]
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": value1['name'],
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+ value2 = list(objects["objects"].values())[0]
+ assert req.status_code == 200
+ assert value1['id'] == value2['id']
+ assert value1['name'] == value2['name']
+
+
+def test_perimeter_add_same_object_perimeter_id_with_new_policy_id():
+ client = utilities.register_client()
+ req, objects = add_objects(client, "testuser")
+ value1 = list(objects["objects"].values())[0]
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": value1['name'],
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data,
+ perimeter_id=value1['id'])
+ value2 = list(objects["objects"].values())[0]
+ assert req.status_code == 200
+ assert value1['id'] == value2['id']
+ assert value1['name'] == value2['name']
+
+
+def test_perimeter_add_same_object_perimeter_id_with_different_name():
+ client = utilities.register_client()
+ req, objects = add_objects(client, "testuser")
+ value1 = list(objects["objects"].values())[0]
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": value1['name'] + 'different',
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data,
+ perimeter_id=value1['id'])
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.'
+
+
+def test_perimeter_add_same_object_name_with_same_policy_id():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+ value = list(objects["objects"].values())[0]
+ assert req.status_code == 200
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_perimeter_add_same_object_perimeter_id_with_existed_policy_id_in_list():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+ value = list(objects["objects"].values())[0]
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data,
+ perimeter_id=value['id'])
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_perimeter_update_object_name():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+
+ value1 = list(objects["objects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update"
+ }
+ req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ objects = utilities.get_json(req.data)
+ value2 = list(objects["objects"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] + 'update' == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] == value2['description']
+
+
+def test_perimeter_update_object_description():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+
+ value1 = list(objects["objects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ objects = utilities.get_json(req.data)
+ value2 = list(objects["objects"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] + 'update' == value2['description']
+
+
+def test_perimeter_update_object_description_and_name():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+
+ value1 = list(objects["objects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update",
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ objects = utilities.get_json(req.data)
+ value2 = list(objects["objects"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] + 'update' == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] + 'update' == value2['description']
+
+
+def test_perimeter_update_object_wrong_id():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data)
+
+ value1 = list(objects["objects"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update",
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/objects/{}".format(perimeter_id + "wrong"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+
+
+def test_perimeter_update_object_name_with_existed_one():
+ client = utilities.register_client()
+ name = 'testuser' + uuid4().hex
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data1 = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data1)
+ value1 = list(objects["objects"].values())[0]
+
+ name = 'testuser' + uuid4().hex
+
+ data2 = {
+ "name": name,
+ "description": "description of {}".format('testuser'),
+ }
+ req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data2)
+
+ value2 = list(objects["objects"].values())[0]
+ perimeter_id2 = value2['id']
+
+ data3 = {
+ 'name': value1['name']
+ }
+ req = client.patch("/objects/{}".format(perimeter_id2), data=json.dumps(data3),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Object Existing'
def test_perimeter_add_object_without_name():
client = utilities.register_client()
data = {
- "name": "",
+ "name": "<br/>",
"description": "description of {}".format(""),
}
req = client.post("/policies/{}/objects/".format("111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_perimeter_add_object_with_name_contain_spaces():
client = utilities.register_client()
data = {
- "name": "test user",
+ "name": "test<a>user",
"description": "description of {}".format("test user"),
}
req = client.post("/policies/{}/objects/".format("111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_perimeter_delete_object():
client = utilities.register_client()
- req = delete_object(client)
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ object_id = builder.create_object(policy_id)
+ req = client.delete("/policies/{}/objects/{}".format(policy_id, object_id))
assert req.status_code == 200
@@ -199,29 +678,30 @@ def get_actions(client):
return req, actions
-def add_actions(client, name):
- subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy(
- subject_category_name="subject_category1" + uuid4().hex,
- object_category_name="object_category1" + uuid4().hex,
- action_category_name="action_category1" + uuid4().hex,
- meta_rule_name="meta_rule_1" + uuid4().hex,
- model_name="model1" + uuid4().hex)
- data = {
- "name": name + uuid4().hex,
- "description": "description of {}".format(name),
- }
- req = client.post("/policies/{}/actions".format(policyId), data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
- actions = utilities.get_json(req.data)
- return req, actions
+def add_actions(client, name, policy_id=None, data=None, perimeter_id=None):
+ if not policy_id:
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
+ if not data:
+ data = {
+ "name": name + uuid4().hex,
+ "description": "description of {}".format(name),
+ }
+ if not perimeter_id:
+ req = client.post("/policies/{}/actions/".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ else:
+ req = client.post("/policies/{}/actions/{}".format(policy_id, perimeter_id),
+ data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
-def delete_actions(client):
- actions = get_actions(client)
- value = actions[1]['actions']
- id = list(value.keys())[0]
- policy_id = builder.get_policy_id_with_action_assignment()
- return client.delete("/policies/{}/actions/{}".format(policy_id, id))
+ actions = utilities.get_json(req.data)
+ return req, actions
def delete_actions_without_perimeter_id(client):
@@ -242,40 +722,305 @@ def test_perimeter_add_actions():
req, actions = add_actions(client, "testuser")
value = list(actions["actions"].values())[0]
assert req.status_code == 200
- assert "actions" in actions
- assert value['name'] is not None
+ assert value['name']
+
+
+def test_perimeter_add_action_with_wrong_policy_id():
+ client = utilities.register_client()
+ req, actions = add_actions(client, "testuser", policy_id="wrong")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
+
+
+def test_perimeter_add_action_with_policy_id_none():
+ client = utilities.register_client()
+ data = {
+ "name": "testuser" + uuid4().hex,
+ "description": "description of {}".format("testuser"),
+ }
+ req = client.post("/policies/{}/actions/".format(None), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
+
+
+def test_perimeter_add_same_action_name_with_new_policy_id():
+ client = utilities.register_client()
+ req, action = add_actions(client, "testuser")
+ value1 = list(action["actions"].values())[0]
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": value1['name'],
+ "description": "description of {}".format('testuser'),
+ }
+ req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data)
+ value2 = list(action["actions"].values())[0]
+ assert req.status_code == 200
+ assert value1['id'] == value2['id']
+ assert value1['name'] == value2['name']
+
+
+def test_perimeter_add_same_action_perimeter_id_with_new_policy_id():
+ client = utilities.register_client()
+ req, action = add_actions(client, "testuser")
+ value1 = list(action["actions"].values())[0]
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": value1['name'],
+ "description": "description of {}".format('testuser'),
+ }
+ req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data,
+ perimeter_id=value1['id'])
+ value2 = list(action["actions"].values())[0]
+ assert req.status_code == 200
+ assert value1['id'] == value2['id']
+ assert value1['name'] == value2['name']
+
+
+def test_perimeter_add_same_action_perimeter_id_with_different_name():
+ client = utilities.register_client()
+ req, action = add_actions(client, "testuser")
+ value1 = list(action["actions"].values())[0]
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ data = {
+ "name": value1['name'] + 'different',
+ "description": "description of {}".format('testuser'),
+ }
+ req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data,
+ perimeter_id=value1['id'])
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.'
+
+
+def test_perimeter_add_same_action_name_with_same_policy_id():
+ client = utilities.register_client()
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ req, action = add_actions(client, "testuser", policy_id=policy_id1)
+ value1 = list(action["actions"].values())[0]
+ data = {
+ "name": value1['name'],
+ "description": "description of {}".format('testuser'),
+ }
+ req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_perimeter_add_same_action_perimeter_id_with_existed_policy_id_in_list():
+ client = utilities.register_client()
+ policies1 = policy_helper.add_policies()
+ policy_id1 = list(policies1.keys())[0]
+ req, action = add_actions(client, "testuser", policy_id=policy_id1)
+ value1 = list(action["actions"].values())[0]
+ data = {
+ "name": value1['name'],
+ "description": "description of {}".format('testuser'),
+ }
+ req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data,
+ perimeter_id=value1['id'])
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
def test_perimeter_add_actions_without_name():
client = utilities.register_client()
data = {
- "name": "",
+ "name": "<a>",
"description": "description of {}".format(""),
}
req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
def test_perimeter_add_actions_with_name_contain_spaces():
client = utilities.register_client()
data = {
- "name": "test user",
+ "name": "test<a>user",
+ "description": "description of {}".format("test user"),
+ }
+ req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
+
+
+def test_add_subjects_without_policy_id():
+ client = utilities.register_client()
+ data = {
+ "name": "testuser",
+ "description": "description of {}".format("test user"),
+ }
+ req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
+
+
+def test_add_objects_without_policy_id():
+ client = utilities.register_client()
+ data = {
+ "name": "testuser",
+ "description": "description of {}".format("test user"),
+ }
+ req = client.post("/policies/{}/objects".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
+
+
+def test_add_action_without_policy_id():
+ client = utilities.register_client()
+ data = {
+ "name": "testuser",
"description": "description of {}".format("test user"),
}
req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
+
+
+def test_perimeter_update_action_name():
+ client = utilities.register_client()
+ req, actions = add_actions(client, "testuser")
+ value1 = list(actions["actions"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update"
+ }
+ req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subjects = utilities.get_json(req.data)
+ value2 = list(subjects["actions"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] + 'update' == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] == value2['description']
+
+
+def test_perimeter_update_actions_description():
+ client = utilities.register_client()
+ req, actions = add_actions(client, "testuser")
+ value1 = list(actions["actions"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subjects = utilities.get_json(req.data)
+ value2 = list(subjects["actions"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] + 'update' == value2['description']
+
+
+def test_perimeter_update_actions_description_and_name():
+ client = utilities.register_client()
+ req, actions = add_actions(client, "testuser")
+ value1 = list(actions["actions"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update",
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subjects = utilities.get_json(req.data)
+ value2 = list(subjects["actions"].values())[0]
+ assert req.status_code == 200
+ assert value1['name'] + 'update' == value2['name']
+ assert value1['id'] == value2['id']
+ assert value1['description'] + 'update' == value2['description']
+
+
+def test_perimeter_update_action_wrong_id():
+ client = utilities.register_client()
+ req, actions = add_actions(client, "testuser")
+ value1 = list(actions["actions"].values())[0]
+ perimeter_id = value1['id']
+ data = {
+ 'name': value1['name'] + "update",
+ 'description': value1['description'] + "update"
+ }
+ req = client.patch("/actions/{}".format(perimeter_id + "wrong"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.'
+
+
+def test_perimeter_update_action_name_with_existed_one():
+ client = utilities.register_client()
+ req, actions = add_actions(client, "testuser")
+ value1 = list(actions["actions"].values())[0]
+ req, actions = add_actions(client, "testuser")
+ value2 = list(actions["actions"].values())[0]
+ perimeter_id2 = value2['id']
+ data = {
+ 'name': value1['name'],
+ }
+ req = client.patch("/actions/{}".format(perimeter_id2), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Action Existing'
def test_perimeter_delete_actions():
client = utilities.register_client()
- req = delete_actions(client)
+
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+ action_id = builder.create_action(policy_id)
+ req = client.delete("/policies/{}/actions/{}".format(policy_id, action_id))
assert req.status_code == 200
+def test_delete_subject_without_policy():
+ client = utilities.register_client()
+
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+
+ action_id = builder.create_action(policy_id)
+
+ req = client.delete("/subjects/{}".format(action_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
+
+
+def test_delete_objects_without_policy():
+ client = utilities.register_client()
+
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+
+ action_id = builder.create_action(policy_id)
+
+ req = client.delete("/objects/{}".format(action_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
+
+
+def test_delete_actions_without_policy():
+ client = utilities.register_client()
+
+ policies = policy_helper.add_policies()
+ policy_id = list(policies.keys())[0]
+
+ action_id = builder.create_action(policy_id)
+
+ req = client.delete("/actions/{}".format(action_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
+
+
def test_perimeter_delete_actions_without_perimeter_id():
client = utilities.register_client()
req = delete_actions_without_perimeter_id(client)
diff --git a/moon_manager/tests/unit_python/api/test_policies.py b/moon_manager/tests/unit_python/api/test_policies.py
index cd50f4c7..76161d53 100644
--- a/moon_manager/tests/unit_python/api/test_policies.py
+++ b/moon_manager/tests/unit_python/api/test_policies.py
@@ -7,6 +7,8 @@ import json
from uuid import uuid4
import api.utilities as utilities
from helpers import model_helper
+from helpers import policy_helper
+from helpers import data_builder
def get_policies(client):
@@ -16,7 +18,7 @@ def get_policies(client):
def add_policies(client, name):
- req = model_helper.add_model(model_id="mls_model_id"+uuid4().hex)
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
model_id = list(req.keys())[0]
data = {
"name": name,
@@ -30,14 +32,6 @@ def add_policies(client, name):
return req, policies
-def delete_policies(client, name):
- request, policies = get_policies(client)
- for key, value in policies['policies'].items():
- req = client.delete("/policies/{}".format(key))
- break
- return req
-
-
def delete_policies_without_id(client):
req = client.delete("/policies/{}".format(""))
return req
@@ -63,15 +57,286 @@ def test_add_policies():
assert value["description"] == "description of {}".format(policy_name)
+def test_add_policies_without_model():
+ policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": "",
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ assert req.status_code == 200
+
+
+def test_add_policies_with_same_name():
+ name = uuid4().hex
+ policy_name = name
+ client = utilities.register_client()
+ req, policies = add_policies(client, policy_name)
+ assert req.status_code == 200
+ assert isinstance(policies, dict)
+ value = list(policies["policies"].values())[0]
+ assert "policies" in policies
+ assert value['name'] == policy_name
+ assert value["description"] == "description of {}".format(policy_name)
+ client = utilities.register_client()
+ req, policies = add_policies(client, policy_name)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_add_policy_with_empty_name():
+ policy_name = ""
+ client = utilities.register_client()
+ req, policies = add_policies(client, policy_name)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Content Error'
+
+
+def test_update_policies_with_model():
+ policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": "",
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id = next(iter(utilities.get_json(req.data)['policies']))
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name + "-2",
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 200
+ assert json.loads(req.data)['policies'][policy_id]['name'] == policy_name + '-2'
+
+
+def test_update_policies_name_success():
+ policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id = next(iter(utilities.get_json(req.data)['policies']))
+
+ data = {
+ "name": policy_name + "-2",
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 200
+ assert json.loads(req.data)['policies'][policy_id]['name'] == policy_name + '-2'
+
+
+def test_update_policies_model_unused():
+ policy_name = uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id = next(iter(utilities.get_json(req.data)['policies']))
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 200
+
+
+def test_update_policy_name_with_existed_one():
+ policy_name1 = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name1,
+ "description": "description of {}".format(policy_name1),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id1 = next(iter(utilities.get_json(req.data)['policies']))
+
+ policy_name2 = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name2,
+ "description": "description of {}".format(policy_name2),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id2 = next(iter(utilities.get_json(req.data)['policies']))
+
+ data = {
+ "name": policy_name1,
+ "description": "description of {}".format(policy_name1),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.patch("/policies/{}".format(policy_id2), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Policy Already Exists'
+
+
+def test_update_policies_with_empty_name():
+ policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id = next(iter(utilities.get_json(req.data)['policies']))
+
+ data = {
+ "name": "",
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Content Error'
+
+
+def test_update_policies_with_blank_model():
+ policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies/", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ policy_id = next(iter(utilities.get_json(req.data)['policies']))
+
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": "",
+ "genre": "genre"
+ }
+
+ req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 200
+
+
+def test_update_policies_connected_to_rules_with_blank_model():
+ client = utilities.register_client()
+ req, rules, policy_id = data_builder.add_rules(client)
+ req = client.get("/policies")
+ data = utilities.get_json(req.data)
+ for policy_obj_id in data['policies']:
+ if policy_obj_id == policy_id:
+ policy = data['policies'][policy_obj_id]
+ policy['model_id'] = ''
+ req = client.patch("/policies/{}".format(policy_id), data=json.dumps(policy),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy update error'
+
+
def test_delete_policies():
client = utilities.register_client()
- req = delete_policies(client, "testuser")
+
+ policy = policy_helper.add_policies()
+ policy_id = list(policy.keys())[0]
+
+ req = client.delete("/policies/{}".format(policy_id))
assert req.status_code == 200
+def test_delete_policy_with_dependencies_rule():
+ client = utilities.register_client()
+ req, rules, policy_id = data_builder.add_rules(client)
+ req = client.delete("/policies/{}".format(policy_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy With Rule Error'
+
+
+def test_delete_policy_with_dependencies_subject_data():
+ client = utilities.register_client()
+ req, rules, policy_id = data_builder.add_rules(client)
+ req = client.delete("/policies/{}/rules/{}".format(policy_id, next(iter(rules['rules']))))
+ assert req.status_code == 200
+ req = client.delete("/policies/{}".format(policy_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy With Data Error'
+
+
+def test_delete_policy_with_dependencies_perimeter():
+ client = utilities.register_client()
+ policy = policy_helper.add_policies()
+ policy_id = next(iter(policy))
+
+ data = {
+ "name": 'testuser'+uuid4().hex,
+ "description": "description of {}".format(uuid4().hex),
+ "password": "password for {}".format(uuid4().hex),
+ "email": "{}@moon".format(uuid4().hex)
+ }
+ req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ assert req.status_code == 200
+ req = client.delete("/policies/{}".format(policy_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy With Perimeter Error'
+
+
def test_delete_policies_without_id():
client = utilities.register_client()
req = delete_policies_without_id(client)
assert req.status_code == 400
assert json.loads(req.data)["message"] == '400: Policy Unknown'
-
diff --git a/moon_manager/tests/unit_python/api/test_rules.py b/moon_manager/tests/unit_python/api/test_rules.py
index af1501e4..a3c21839 100644
--- a/moon_manager/tests/unit_python/api/test_rules.py
+++ b/moon_manager/tests/unit_python/api/test_rules.py
@@ -11,31 +11,11 @@ def get_rules(client, policy_id):
return req, rules
-def add_rules(client):
- sub_id, obj_id, act_id, meta_rule_id, policy_id = builder.create_new_policy("sub_cat" + uuid4().hex,
- "obj_cat" + uuid4().hex,
- "act_cat" + uuid4().hex)
- sub_data_id = builder.create_subject_data(policy_id, sub_id)
- obj_data_id = builder.create_object_data(policy_id, obj_id)
- act_data_id = builder.create_action_data(policy_id, act_id)
- data = {
- "meta_rule_id": meta_rule_id,
- "rule": [sub_data_id, obj_data_id, act_data_id],
- "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_policy_id(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule()
data = {
- "meta_rule_id": "meta_rule_id",
- "rule": ["sub_data_id", "obj_data_id", "act_data_id"],
+ "meta_rule_id": meta_rule_id,
+ "rule": [subject_category_id, object_category_id, action_category_id],
"instructions": (
{"decision": "grant"},
),
@@ -93,7 +73,7 @@ def test_get_rules():
def test_add_rules():
client = utilities.register_client()
- req, rules = add_rules(client, )
+ req, rules, policy = builder.add_rules(client, )
assert req.status_code == 200
@@ -103,13 +83,13 @@ def test_add_rules_without_policy_id():
assert req.status_code == 400
assert json.loads(req.data)["message"] == "400: Policy Unknown"
-
-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 == 400
- assert json.loads(req.data)["message"] == "Key: 'meta_rule_id', [Empty String]"
+#
+# 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 == 400
+# assert json.loads(req.data)["message"] == "Key: 'meta_rule_id', [Empty String]"
def test_add_rules_without_rule():
@@ -122,8 +102,9 @@ def test_add_rules_without_rule():
def test_delete_rules_with_invalid_parameters():
client = utilities.register_client()
- rules = delete_rules(client, "", "")
- assert rules.status_code == 404
+ req = delete_rules(client, "", "")
+ assert req.status_code == 404
+ # assert json.loads(req.data)["message"] == 'Invalid Key :rule not found'
def test_delete_rules_without_policy_id():
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 d754b976..6e93ed28 100644
--- a/moon_manager/tests/unit_python/api/test_unit_models.py
+++ b/moon_manager/tests/unit_python/api/test_unit_models.py
@@ -6,6 +6,8 @@
import json
import api.utilities as utilities
from helpers import data_builder as builder
+from helpers import policy_helper
+from helpers import model_helper
from uuid import uuid4
@@ -15,16 +17,15 @@ def get_models(client):
return req, models
-def add_models(client, name):
- subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(
- subject_category_name="subject_category"+uuid4().hex,
- object_category_name="object_category"+uuid4().hex, action_category_name="action_category"+uuid4().hex,
- meta_rule_name="meta_rule" + uuid4().hex)
- data = {
- "name": name,
- "description": "description of {}".format(name),
- "meta_rules": [meta_rule_id]
- }
+def add_models(client, name, data=None):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule()
+
+ if not data:
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "meta_rules": [meta_rule_id]
+ }
req = client.post("/models", data=json.dumps(data),
headers={'Content-Type': 'application/json'})
models = utilities.get_json(req.data)
@@ -32,10 +33,7 @@ def add_models(client, name):
def update_model(client, name, model_id):
- subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(
- subject_category_name="subject_category" + uuid4().hex,
- object_category_name="object_category" + uuid4().hex, action_category_name="action_category" + uuid4().hex,
- meta_rule_name="meta_rule" + uuid4().hex)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule()
data = {
"name": name,
@@ -60,13 +58,26 @@ def add_model_without_meta_rules_ids(client, name):
return req, models
-def update_model_without_meta_rules_ids(client, name):
+def add_model_with_empty_meta_rule_id(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, model_id):
+ name = "model_id" + uuid4().hex
data = {
"name": name,
"description": "description of {}".format(name),
"meta_rules": []
}
- req = client.patch("/models", data=json.dumps(data),
+ 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
@@ -86,6 +97,24 @@ def delete_models_without_id(client):
return req
+def test_delete_model_assigned_to_policy():
+ policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
+ req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(req.keys())[0]
+ data = {
+ "name": policy_name,
+ "description": "description of {}".format(policy_name),
+ "model_id": model_id,
+ "genre": "genre"
+ }
+ req = client.post("/policies", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ req = client.delete("/models/{}".format(model_id))
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Model With Policy Error'
+
+
def clean_models():
client = utilities.register_client()
req, models = get_models(client)
@@ -121,6 +150,64 @@ def test_delete_models():
assert req.status_code == 200
+def test_update_models_with_assigned_policy():
+ client = utilities.register_client()
+
+ model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(model.keys())[0]
+ value = {
+ "name": "test_policy" + uuid4().hex,
+ "model_id": model_id,
+ "description": "test",
+ }
+ policy = policy_helper.add_policies(value=value)
+ data = {
+ "name": "model_" + uuid4().hex,
+ "description": "description of model_2",
+ "meta_rules": []
+ }
+ req = client.patch("/models/{}".format(model_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Model With Policy Error"
+
+
+def test_update_models_with_no_assigned_policy():
+ client = utilities.register_client()
+
+ model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(model.keys())[0]
+
+ data = {
+ "name": "model_" + uuid4().hex,
+ "description": "description of model_2",
+ "meta_rules": []
+ }
+ req = client.patch("/models/{}".format(model_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ assert req.status_code == 200
+
+
+def test_add_models_with_meta_rule_key():
+ client = utilities.register_client()
+
+ model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex)
+ model_id = list(model.keys())[0]
+
+ data = {
+ "name": "model_" + uuid4().hex,
+ "description": "description of model_2",
+
+ }
+ req = client.patch("/models/{}".format(model_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Invalid Key :meta_rules not found"
+
+
def test_delete_models_without_id():
client = utilities.register_client()
req = delete_models_without_id(client)
@@ -128,28 +215,80 @@ def test_delete_models_without_id():
assert json.loads(req.data)["message"] == "400: Model Unknown"
-def test_add_model_with_empty_user():
+def test_add_model_with_empty_name():
+ clean_models()
+ client = utilities.register_client()
+ req, models = add_models(client, "<br/>")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
+
+
+def test_add_model_with_name_contain_space():
+ clean_models()
+ client = utilities.register_client()
+ req, models = add_models(client, "test<br>user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]"
+
+
+def test_add_model_with_name_space():
clean_models()
client = utilities.register_client()
- req, models = add_models(client, "")
+ req, models = add_models(client, " ")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req.data)["message"] == '400: Model Unknown'
-def test_add_model_with_user_contain_space():
+def test_add_model_with_empty_meta_rule_id():
clean_models()
client = utilities.register_client()
- req, models = add_models(client, "test user")
+ req, meta_rules = add_model_with_empty_meta_rule_id(client, "testuser")
assert req.status_code == 400
- assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+ assert json.loads(req.data)["message"] == '400: Meta Rule Unknown'
+
+
+def test_add_model_with_existed_name():
+ clean_models()
+ client = utilities.register_client()
+ name = uuid4().hex
+ req, models = add_models(client, name)
+ assert req.status_code == 200
+ req, models = add_models(client, name)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Model Error'
+
+
+def test_add_model_with_existed_meta_rules_list():
+ clean_models()
+ client = utilities.register_client()
+ name = uuid4().hex
+
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule()
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "meta_rules": [meta_rule_id]
+ }
+ name = uuid4().hex
+ req, models = add_models(client=client, name=name, data=data)
+ assert req.status_code == 200
+
+ data = {
+ "name": name,
+ "description": "description of {}".format(name),
+ "meta_rules": [meta_rule_id]
+ }
+ req, models = add_models(client=client, name=name, data=data)
+ assert req.status_code == 409
+ assert json.loads(req.data)["message"] == '409: Model Error'
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 == 400
- assert json.loads(req.data)["message"] == "Key: 'meta_rules', [Empty Container]"
+ assert req.status_code == 200
+ # assert json.loads(req.data)["message"] == "Key: 'meta_rules', [Empty Container]"
def test_update_model():
@@ -164,6 +303,26 @@ def test_update_model():
delete_models(client, "testuser")
+def test_update_model_name_with_space():
+ clean_models()
+ client = utilities.register_client()
+ req = add_models(client, "testuser")
+ model_id = list(req[1]['models'])[0]
+ req_update = update_model(client, " ", model_id)
+ assert req_update[0].status_code == 400
+ assert req_update[1]["message"] == '400: Model Unknown'
+
+
+def test_update_model_with_empty_name():
+ clean_models()
+ client = utilities.register_client()
+ req = add_models(client, "testuser")
+ model_id = list(req[1]['models'])[0]
+ req_update = update_model(client, "", model_id)
+ assert req_update[0].status_code == 400
+ assert req_update[1]['message'] == '400: Model Unknown'
+
+
def test_update_meta_rules_without_id():
clean_models()
client = utilities.register_client()
@@ -172,15 +331,22 @@ def test_update_meta_rules_without_id():
assert json.loads(req_update[0].data)["message"] == "400: Model Unknown"
-def test_update_meta_rules_without_user():
+def test_update_meta_rules_without_name():
client = utilities.register_client()
- req_update = update_model(client, "", "")
+ req_update = update_model(client, "<a></a>", "1234567")
assert req_update[0].status_code == 400
- assert json.loads(req_update[0].data)["message"] == "Key: 'name', [Empty String]"
+ assert json.loads(req_update[0].data)[
+ "message"] == "Key: 'name', [Forbidden characters in string]"
def test_update_meta_rules_without_meta_rules():
+ value = {
+ "name": "mls_model_id" + uuid4().hex,
+ "description": "test",
+ "meta_rules": []
+ }
+ model = model_helper.add_model(value=value)
+ model_id = list(model.keys())[0]
client = utilities.register_client()
- req_update = update_model_without_meta_rules_ids(client, "testuser")
- assert req_update[0].status_code == 400
- assert json.loads(req_update[0].data)["message"] == "Key: 'meta_rules', [Empty Container]"
+ req_update = update_model_without_meta_rules_ids(client, model_id)
+ assert req_update[0].status_code == 200
diff --git a/moon_manager/tests/unit_python/conftest.py b/moon_manager/tests/unit_python/conftest.py
index d9899231..90a27e54 100644
--- a/moon_manager/tests/unit_python/conftest.py
+++ b/moon_manager/tests/unit_python/conftest.py
@@ -153,6 +153,24 @@ PODS = {
}
}
+SLAVES = {
+ "slaves": [
+ {
+ "context":
+ {
+ "cluster": "kubernetes",
+ "user": "kubernetes-admin"
+ },
+ "name": "kubernetes-admin@kubernetes",
+ "configured": True,
+ "wrapper_name": "mywrapper",
+ "ip": "NC",
+ "port": 31002,
+ "internal_port": 8080
+ }
+ ]
+}
+
def get_b64_conf(component=None):
if component in CONF:
@@ -211,6 +229,10 @@ def no_requests(monkeypatch):
json=PODS
)
m.register_uri(
+ 'GET', 'http://localhost/slaves',
+ json=SLAVES
+ )
+ m.register_uri(
'DELETE', 'http://orchestrator:8083/pods/{}'.format(list([PODS['pods'].keys()])[0]),
headers={"content-type": "application/json"}
)
diff --git a/moon_manager/tests/unit_python/helpers/data_builder.py b/moon_manager/tests/unit_python/helpers/data_builder.py
index 2a7c5979..91808cbe 100644
--- a/moon_manager/tests/unit_python/helpers/data_builder.py
+++ b/moon_manager/tests/unit_python/helpers/data_builder.py
@@ -10,6 +10,7 @@ from helpers import model_helper
from .meta_rule_helper import *
import api.utilities as utilities
import json
+from uuid import uuid4
def create_subject_category(name):
@@ -60,31 +61,57 @@ def create_pdp(policies_ids):
return value
-def create_new_policy(subject_category_name="subjectCategory", object_category_name="objectCategory",
- action_category_name="actionCategory",
- model_name="test_model" + uuid4().hex, policy_name="policy_1" + uuid4().hex,
- meta_rule_name="meta_rule1" + uuid4().hex):
+def create_new_policy(subject_category_name=None, object_category_name=None,
+ action_category_name=None, model_name=None, policy_name=None,
+ meta_rule_name=None):
+ if not subject_category_name:
+ subject_category_name = "subjectCategory_" + uuid4().hex
+ if not object_category_name:
+ object_category_name = "objectCategory_" + uuid4().hex
+ if not action_category_name:
+ action_category_name = "actionCategory_" + uuid4().hex
+
+ if not meta_rule_name:
+ meta_rule_name = "meta_rule_" + uuid4().hex
+
+ if not model_name:
+ model_name = "model_name_" + uuid4().hex
+ if not policy_name:
+ policy_name = "policy_name_" + uuid4().hex
+
subject_category_id, object_category_id, action_category_id, meta_rule_id = create_new_meta_rule(
subject_category_name=subject_category_name + uuid4().hex,
object_category_name=object_category_name + uuid4().hex,
- action_category_name=action_category_name + uuid4().hex, meta_rule_name=meta_rule_name + uuid4().hex)
- model = model_helper.add_model(value=create_model(meta_rule_id, model_name))
+ action_category_name=action_category_name + uuid4().hex,
+ meta_rule_name=meta_rule_name + uuid4().hex
+ )
+
+ model = model_helper.add_model(value=create_model(meta_rule_id, model_name + uuid4().hex))
model_id = list(model.keys())[0]
- value = create_policy(model_id, policy_name)
+ value = create_policy(model_id, policy_name + uuid4().hex)
policy = add_policies(value=value)
assert policy
policy_id = list(policy.keys())[0]
return subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id
-def create_new_meta_rule(subject_category_name="subjectCategory", object_category_name="objectCategory",
- action_category_name="actionCategory",
- meta_rule_name="meta_rule1" + uuid4().hex):
+def create_new_meta_rule(subject_category_name=None, object_category_name=None,
+ action_category_name=None, meta_rule_name=None):
+ if not subject_category_name:
+ subject_category_name = "subjectCategory_" + uuid4().hex
+ if not object_category_name:
+ object_category_name = "objectCategory_" + uuid4().hex
+ if not action_category_name:
+ action_category_name = "actionCategory_" + uuid4().hex
+
+ if not meta_rule_name:
+ meta_rule_name = "meta_rule_" + uuid4().hex
+
subject_category_id = create_subject_category(subject_category_name)
object_category_id = create_object_category(object_category_name)
action_category_id = create_action_category(action_category_name)
value = {"name": meta_rule_name,
- "algorithm": "name of the meta rule algorithm",
+ "description": "name of the meta rule algorithm",
"subject_categories": [subject_category_id],
"object_categories": [object_category_id],
"action_categories": [action_category_id]
@@ -125,7 +152,8 @@ def create_subject_data(policy_id, category_id):
"name": "subject-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- subject_data = add_subject_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ subject_data = add_subject_data(policy_id=policy_id, category_id=category_id, value=value).get(
+ 'data')
assert subject_data
return list(subject_data.keys())[0]
@@ -135,7 +163,8 @@ def create_object_data(policy_id, category_id):
"name": "object-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- object_data = add_object_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ object_data = add_object_data(policy_id=policy_id, category_id=category_id, value=value).get(
+ 'data')
return list(object_data.keys())[0]
@@ -144,7 +173,8 @@ def create_action_data(policy_id, category_id):
"name": "action-type",
"description": {"vm-action": "", "storage-action": "", },
}
- action_data = add_action_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ action_data = add_action_data(policy_id=policy_id, category_id=category_id, value=value).get(
+ 'data')
return list(action_data.keys())[0]
@@ -207,3 +237,24 @@ def get_policy_id_with_action_assignment():
client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
return policy_id
+
+
+def add_rules(client):
+ sub_id, obj_id, act_id, meta_rule_id, policy_id = create_new_policy("sub_cat" + uuid4().hex,
+ "obj_cat" + uuid4().hex,
+ "act_cat" + uuid4().hex)
+ sub_data_id = create_subject_data(policy_id, sub_id)
+ obj_data_id = create_object_data(policy_id, obj_id)
+ act_data_id = create_action_data(policy_id, act_id)
+ data = {
+ "meta_rule_id": meta_rule_id,
+ "rule": [sub_data_id, obj_data_id, act_data_id],
+ "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, policy_id
diff --git a/moon_manager/tests/unit_python/helpers/data_helper.py b/moon_manager/tests/unit_python/helpers/data_helper.py
index da6b9376..e1c05640 100644
--- a/moon_manager/tests/unit_python/helpers/data_helper.py
+++ b/moon_manager/tests/unit_python/helpers/data_helper.py
@@ -16,7 +16,7 @@ def add_action_data(policy_id, data_id=None, category_id=None, value=None):
def delete_action_data(policy_id, data_id):
from python_moondb.core import PolicyManager
- PolicyManager.delete_action_data("", policy_id, data_id)
+ PolicyManager.delete_action_data("", policy_id=policy_id, data_id=data_id)
def get_object_data(policy_id, data_id=None, category_id=None):
@@ -31,7 +31,7 @@ def add_object_data(policy_id, data_id=None, category_id=None, value=None):
def delete_object_data(policy_id, data_id):
from python_moondb.core import PolicyManager
- PolicyManager.delete_object_data("", policy_id, data_id)
+ PolicyManager.delete_object_data("", policy_id=policy_id, data_id=data_id)
def get_subject_data(policy_id, data_id=None, category_id=None):
@@ -46,7 +46,7 @@ def add_subject_data(policy_id, data_id=None, category_id=None, value=None):
def delete_subject_data(policy_id, data_id):
from python_moondb.core import PolicyManager
- PolicyManager.delete_subject_data("", policy_id, data_id)
+ PolicyManager.delete_subject_data("", policy_id=policy_id, data_id=data_id)
def get_actions(policy_id, perimeter_id=None):
diff --git a/moon_manager/tests/unit_python/helpers/model_helper.py b/moon_manager/tests/unit_python/helpers/model_helper.py
index d2ffb85b..73808e03 100644
--- a/moon_manager/tests/unit_python/helpers/model_helper.py
+++ b/moon_manager/tests/unit_python/helpers/model_helper.py
@@ -15,11 +15,8 @@ def get_models(model_id=None):
def add_model(model_id=None, value=None):
from python_moondb.core import ModelManager
if not value:
- subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(
- subject_category_name="subject_category1"+uuid4().hex,
- object_category_name="object_category1"+uuid4().hex,
- action_category_name="action_category1"+uuid4().hex)
- name = "MLS" if model_id is None else "MLS " + model_id
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule()
+ name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id
value = {
"name": name,
"description": "test",
diff --git a/moon_manager/tests/unit_python/helpers/policy_helper.py b/moon_manager/tests/unit_python/helpers/policy_helper.py
index c932ee3a..eddd0b8d 100644
--- a/moon_manager/tests/unit_python/helpers/policy_helper.py
+++ b/moon_manager/tests/unit_python/helpers/policy_helper.py
@@ -3,6 +3,8 @@
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+from uuid import uuid4
+
def get_policies():
from python_moondb.core import PolicyManager
return PolicyManager.get_policies("admin")
@@ -12,7 +14,7 @@ def add_policies(policy_id=None, value=None):
from python_moondb.core import PolicyManager
if not value:
value = {
- "name": "test_policy",
+ "name": "test_policy"+ uuid4().hex,
"model_id": "",
"genre": "authz",
"description": "test",
diff --git a/moon_manager/tests/unit_python/requirements.txt b/moon_manager/tests/unit_python/requirements.txt
index 6c6e5bb8..d6f190e4 100644
--- a/moon_manager/tests/unit_python/requirements.txt
+++ b/moon_manager/tests/unit_python/requirements.txt
@@ -1,5 +1,5 @@
flask
flask_cors
flask_restful
-python_moondb
-python_moonutilities
+python_moondb==1.2.20
+python_moonutilities==1.4.20