aboutsummaryrefslogtreecommitdiffstats
path: root/moon_manager/moon_manager
diff options
context:
space:
mode:
Diffstat (limited to 'moon_manager/moon_manager')
-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
18 files changed, 417 insertions, 270 deletions
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")