Move Manager interface from a RabbitMQq connection to a HTTP connection 41/41841/1
authorasteroide <thomas.duval@orange.com>
Wed, 13 Sep 2017 09:15:32 +0000 (11:15 +0200)
committerasteroide <thomas.duval@orange.com>
Wed, 13 Sep 2017 09:15:32 +0000 (11:15 +0200)
Change-Id: I03508303cae86d685e68b61839190af3783c4bf7

16 files changed:
moonv4/moon_manager/Dockerfile
moonv4/moon_manager/moon_manager/api/assignments.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/api/data.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/api/generic.py
moonv4/moon_manager/moon_manager/api/master.py [deleted file]
moonv4/moon_manager/moon_manager/api/meta_data.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/api/meta_rules.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/api/models.py
moonv4/moon_manager/moon_manager/api/pdp.py
moonv4/moon_manager/moon_manager/api/perimeter.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/api/policies.py
moonv4/moon_manager/moon_manager/api/rules.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/http_server.py [new file with mode: 0644]
moonv4/moon_manager/moon_manager/messenger.py [deleted file]
moonv4/moon_manager/moon_manager/server.py
moonv4/moon_manager/requirements.txt

index 71b1954..3e1a65a 100644 (file)
@@ -1,12 +1,11 @@
 FROM ubuntu:latest
 
 RUN apt update && apt install python3.5 python3-pip -y
-RUN pip3 install moon_utilities moon_db pip --upgrade
+RUN pip3 install pip --upgrade
 
 ADD . /root
 WORKDIR /root/
 RUN pip3 install -r requirements.txt
-RUN pip install dist/* --upgrade
 RUN pip3 install .
 
 CMD ["python3", "-m", "moon_manager"]
\ No newline at end of file
diff --git a/moonv4/moon_manager/moon_manager/api/assignments.py b/moonv4/moon_manager/moon_manager/api/assignments.py
new file mode 100644 (file)
index 0000000..bc58530
--- /dev/null
@@ -0,0 +1,334 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Assignments allow to connect data with elements of perimeter
+
+"""
+
+from flask import request
+from flask_restful import Resource
+from oslo_log import log as logging
+from moon_utilities.security_functions import check_auth
+from moon_db.core import PolicyManager
+
+__version__ = "0.2.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class SubjectAssignments(Resource):
+    """
+    Endpoint for subject assignment requests
+    """
+
+    __urls__ = (
+        "/policies/<string:uuid>/subject_assignments",
+        "/policies/<string:uuid>/subject_assignments/",
+        "/policies/<string:uuid>/subject_assignments/<string:perimeter_id>",
+        "/policies/<string:uuid>/subject_assignments/<string:perimeter_id>/<string:category_id>",
+        "/policies/<string:uuid>/subject_assignments/<string:perimeter_id>/<string:category_id>/<string:data_id>",
+    )
+
+    @check_auth
+    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
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the subject
+        :param category_id: uuid of the subject category
+        :param data_id: uuid of the subject scope
+        :param user_id: user ID who do the request
+        :return: {
+            "subject_data_id": {
+                "policy_id": "ID of the policy",
+                "subject_id": "ID of the subject",
+                "category_id": "ID of the category",
+                "assignments": "Assignments list (list of data_id)",
+            }
+        }
+        :internal_api: get_subject_assignments
+        """
+        # return call(ctx={"id": uuid, "method": "get_subject_assignments", "perimeter_id": perimeter_id, "category_id": category_id, "user_id": user_id},
+        #             args={"data_id": data_id})
+        try:
+            # if "perimeter_name" in ctx:
+            #     ctx["perimeter_id"] = self.__get_subject_id(ctx, ctx['perimeter_name'])
+            data = PolicyManager.get_subject_assignments(user_id=user_id, policy_id=uuid,
+                                                         subject_id=perimeter_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subject_assignments": data}
+
+    @check_auth
+    def post(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
+        """Create a subject assignment.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the subject (not used here)
+        :param category_id: uuid of the subject category (not used here)
+        :param data_id: uuid of the subject scope (not used here)
+        :param user_id: user ID who do the request
+        :request body: {
+            "id": "UUID of the subject",
+            "category_id": "UUID of the category"
+            "data_id": "UUID of the scope"
+        }
+        :return: {
+            "subject_data_id": {
+                "policy_id": "ID of the policy",
+                "subject_id": "ID of the subject",
+                "category_id": "ID of the category",
+                "assignments": "Assignments list (list of data_id)",
+            }
+        }
+        :internal_api: update_subject_assignment
+        """
+        try:
+            data_id = request.json.get("data_id")
+            category_id = request.json.get("category_id")
+            perimeter_id = request.json.get("id")
+            data = PolicyManager.add_subject_assignment(user_id=user_id, policy_id=uuid,
+                                                        subject_id=perimeter_id, category_id=category_id,
+                                                        data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subject_assignments": data}
+
+    @check_auth
+    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
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the subject
+        :param category_id: uuid of the subject category
+        :param data_id: uuid of the subject scope
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_subject_assignment
+        """
+        try:
+            data = PolicyManager.delete_subject_assignment(user_id=user_id, policy_id=uuid,
+                                                           subject_id=perimeter_id, category_id=category_id,
+                                                           data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class ObjectAssignments(Resource):
+    """
+    Endpoint for object assignment requests
+    """
+
+    __urls__ = (
+        "/policies/<string:uuid>/object_assignments",
+        "/policies/<string:uuid>/object_assignments/",
+        "/policies/<string:uuid>/object_assignments/<string:perimeter_id>",
+        "/policies/<string:uuid>/object_assignments/<string:perimeter_id>/<string:category_id>",
+        "/policies/<string:uuid>/object_assignments/<string:perimeter_id>/<string:category_id>/<string:data_id>",
+    )
+
+    @check_auth
+    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
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the object
+        :param category_id: uuid of the object category
+        :param data_id: uuid of the object scope
+        :param user_id: user ID who do the request
+        :return: {
+            "object_data_id": {
+                "policy_id": "ID of the policy",
+                "object_id": "ID of the object",
+                "category_id": "ID of the category",
+                "assignments": "Assignments list (list of data_id)",
+            }
+        }
+        :internal_api: get_object_assignments
+        """
+        try:
+            data = PolicyManager.get_object_assignments(user_id=user_id, policy_id=uuid,
+                                                        object_id=perimeter_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"object_assignments": data}
+
+    @check_auth
+    def post(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
+        """Create an object assignment.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the object (not used here)
+        :param category_id: uuid of the object category (not used here)
+        :param data_id: uuid of the object scope (not used here)
+        :param user_id: user ID who do the request
+        :request body: {
+            "id": "UUID of the action",
+            "category_id": "UUID of the category"
+            "data_id": "UUID of the scope"
+        }
+        :return: {
+            "object_data_id": {
+                "policy_id": "ID of the policy",
+                "object_id": "ID of the object",
+                "category_id": "ID of the category",
+                "assignments": "Assignments list (list of data_id)",
+            }
+        }
+        :internal_api: update_object_assignment
+        """
+        try:
+            data_id = request.json.get("data_id")
+            category_id = request.json.get("category_id")
+            perimeter_id = request.json.get("id")
+            data = PolicyManager.add_object_assignment(user_id=user_id, policy_id=uuid,
+                                                       object_id=perimeter_id, category_id=category_id,
+                                                       data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"object_assignments": data}
+
+    @check_auth
+    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
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the object
+        :param category_id: uuid of the object category
+        :param data_id: uuid of the object scope
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_object_assignment
+        """
+        try:
+            data = PolicyManager.delete_object_assignment(user_id=user_id, policy_id=uuid,
+                                                          object_id=perimeter_id, category_id=category_id,
+                                                          data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class ActionAssignments(Resource):
+    """
+    Endpoint for action assignment requests
+    """
+
+    __urls__ = (
+        "/policies/<string:uuid>/action_assignments",
+        "/policies/<string:uuid>/action_assignments/",
+        "/policies/<string:uuid>/action_assignments/<string:perimeter_id>",
+        "/policies/<string:uuid>/action_assignments/<string:perimeter_id>/<string:category_id>",
+        "/policies/<string:uuid>/action_assignments/<string:perimeter_id>/<string:category_id>/<string:data_id>",
+    )
+
+    @check_auth
+    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
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the action
+        :param category_id: uuid of the action category
+        :param data_id: uuid of the action scope
+        :param user_id: user ID who do the request
+        :return: {
+            "action_data_id": {
+                "policy_id": "ID of the policy",
+                "object_id": "ID of the action",
+                "category_id": "ID of the category",
+                "assignments": "Assignments list (list of data_id)",
+            }
+        }
+        :internal_api: get_action_assignments
+        """
+        try:
+            data = PolicyManager.get_action_assignments(user_id=user_id, policy_id=uuid,
+                                                        action_id=perimeter_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"action_assignments": data}
+
+    @check_auth
+    def post(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
+        """Create an action assignment.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the action (not used here)
+        :param category_id: uuid of the action category (not used here)
+        :param data_id: uuid of the action scope (not used here)
+        :param user_id: user ID who do the request
+        :request body: {
+            "id": "UUID of the action",
+            "category_id": "UUID of the category",
+            "data_id": "UUID of the scope"
+        }
+        :return: {
+            "action_data_id": {
+                "policy_id": "ID of the policy",
+                "object_id": "ID of the action",
+                "category_id": "ID of the category",
+                "assignments": "Assignments list (list of data_id)",
+            }
+        }
+        :internal_api: update_action_assignment
+        """
+        try:
+            data_id = request.json.get("data_id")
+            category_id = request.json.get("category_id")
+            perimeter_id = request.json.get("id")
+            data = PolicyManager.add_action_assignment(user_id=user_id, policy_id=uuid,
+                                                       action_id=perimeter_id, category_id=category_id,
+                                                       data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"action_assignments": data}
+
+    @check_auth
+    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
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the action
+        :param category_id: uuid of the action category
+        :param data_id: uuid of the action scope
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_action_assignment
+        """
+        try:
+            data = PolicyManager.delete_action_assignment(user_id=user_id, policy_id=uuid,
+                                                          action_id=perimeter_id, category_id=category_id,
+                                                          data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
diff --git a/moonv4/moon_manager/moon_manager/api/data.py b/moonv4/moon_manager/moon_manager/api/data.py
new file mode 100644 (file)
index 0000000..fbf26fd
--- /dev/null
@@ -0,0 +1,314 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Data are elements used to create rules
+
+"""
+
+from flask import request
+from flask_restful import Resource
+from oslo_log import log as logging
+from moon_utilities.security_functions import check_auth
+from moon_db.core import PolicyManager
+
+__version__ = "0.2.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class SubjectData(Resource):
+    """
+    Endpoint for subject data requests
+    """
+
+    __urls__ = (
+        "/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>",
+    )
+
+    @check_auth
+    def get(self, uuid=None, category_id=None, data_id=None, user_id=None):
+        """Retrieve all subject categories or a specific one if sid is given for a given policy
+
+        :param uuid: uuid of the policy
+        :param category_id: uuid of the subject category
+        :param data_id: uuid of the subject data
+        :param user_id: user ID who do the request
+        :return: [{
+            "policy_id": "policy_id1",
+            "category_id": "category_id1",
+            "data": {
+                "subject_data_id": {
+                    "name": "name of the data",
+                    "description": "description of the data"
+                }
+            }
+        }]
+        :internal_api: get_subject_data
+        """
+        try:
+            data = PolicyManager.get_subject_data(user_id=user_id, policy_id=uuid,
+                                                  category_id=category_id, data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subject_data": data}
+
+    @check_auth
+    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
+        :param category_id: uuid of the subject category
+        :param data_id: uuid of the subject data
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the data",
+            "description": "description of the data"
+        }
+        :return: {
+            "policy_id": "policy_id1",
+            "category_id": "category_id1",
+            "data": {
+                "subject_data_id": {
+                    "name": "name of the data",
+                    "description": "description of the data"
+                }
+            }
+        }
+        :internal_api: add_subject_data
+        """
+        try:
+            data = PolicyManager.set_subject_data(user_id=user_id, policy_id=uuid,
+                                                  category_id=category_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subject_data": data}
+
+    @check_auth
+    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
+        :param category_id: uuid of the subject category
+        :param data_id: uuid of the subject data
+        :param user_id: user ID who do the request
+        :return: [{
+            "result": "True or False",
+            "message": "optional message"
+        }]
+        :internal_api: delete_subject_data
+        """
+        try:
+            data = PolicyManager.delete_subject_data(user_id=user_id, policy_id=uuid,
+                                                     data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class ObjectData(Resource):
+    """
+    Endpoint for object data requests
+    """
+
+    __urls__ = (
+        "/policies/<string:uuid>/object_data",
+        "/policies/<string:uuid>/object_data/",
+        "/policies/<string:uuid>/object_data/<string:category_id>",
+        "/policies/<string:uuid>/object_data/<string:category_id>/<string:data_id>",
+    )
+
+    @check_auth
+    def get(self, uuid=None, category_id=None, data_id=None, user_id=None):
+        """Retrieve all object categories or a specific one if sid is given for a given policy
+
+        :param uuid: uuid of the policy
+        :param category_id: uuid of the object category
+        :param data_id: uuid of the object data
+        :param user_id: user ID who do the request
+        :return: [{
+            "policy_id": "policy_id1",
+            "category_id": "category_id1",
+            "data": {
+                "object_data_id": {
+                    "name": "name of the data",
+                    "description": "description of the data"
+                }
+            }
+        }]
+        :internal_api: get_object_data
+        """
+        try:
+            data = PolicyManager.get_object_data(user_id=user_id, policy_id=uuid,
+                                                 category_id=category_id, data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"object_data": data}
+
+    @check_auth
+    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
+        :param category_id: uuid of the object category
+        :param data_id: uuid of the object data
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the data",
+            "description": "description of the data"
+        }
+        :return: {
+            "policy_id": "policy_id1",
+            "category_id": "category_id1",
+            "data": {
+                "object_data_id": {
+                    "name": "name of the data",
+                    "description": "description of the data"
+                }
+            }
+        }
+        :internal_api: add_object_data
+        """
+        try:
+            data = PolicyManager.add_object_data(user_id=user_id, policy_id=uuid,
+                                                 category_id=category_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"object_data": data}
+
+    @check_auth
+    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
+        :param category_id: uuid of the object category
+        :param data_id: uuid of the object data
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_object_data
+        """
+        try:
+            data = PolicyManager.delete_object_data(user_id=user_id, policy_id=uuid,
+                                                   data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class ActionData(Resource):
+    """
+    Endpoint for action data requests
+    """
+
+    __urls__ = (
+        "/policies/<string:uuid>/action_data",
+        "/policies/<string:uuid>/action_data/",
+        "/policies/<string:uuid>/action_data/<string:category_id>",
+        "/policies/<string:uuid>/action_data/<string:category_id>/<string:data_id>",
+    )
+
+    @check_auth
+    def get(self, uuid=None, category_id=None, data_id=None, user_id=None):
+        """Retrieve all action categories or a specific one if sid is given for a given policy
+
+        :param uuid: uuid of the policy
+        :param category_id: uuid of the action category
+        :param data_id: uuid of the action data
+        :param user_id: user ID who do the request
+        :return: [{
+            "policy_id": "policy_id1",
+            "category_id": "category_id1",
+            "data": {
+                "action_data_id": {
+                    "name": "name of the data",
+                    "description": "description of the data"
+                }
+            }
+        }]
+        :internal_api: get_action_data
+        """
+        try:
+            data = PolicyManager.get_action_data(user_id=user_id, policy_id=uuid,
+                                                 category_id=category_id, data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"action_data": data}
+
+    @check_auth
+    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
+        :param category_id: uuid of the action category
+        :param data_id: uuid of the action data
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the data",
+            "description": "description of the data"
+        }
+        :return: {
+            "policy_id": "policy_id1",
+            "category_id": "category_id1",
+            "data": {
+                "action_data_id": {
+                    "name": "name of the data",
+                    "description": "description of the data"
+                }
+            }
+        }
+        :internal_api: add_action_data
+        """
+        try:
+            data = PolicyManager.add_action_data(user_id=user_id, policy_id=uuid,
+                                                 category_id=category_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"action_data": data}
+
+    @check_auth
+    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
+        :param category_id: uuid of the action category
+        :param data_id: uuid of the action data
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_action_data
+        """
+        try:
+            data = PolicyManager.delete_action_data(user_id=user_id, policy_id=uuid,
+                                                    data_id=data_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
index db61188..ac4f8f1 100644 (file)
 # This software is distributed under the terms and conditions of the 'Apache-2.0'
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Those API are helping API used to manage the Moon platform.
+"""
 
+from flask_restful import Resource, request
+from oslo_log import log as logging
+import moon_manager.api
+from moon_utilities.security_functions import check_auth
 
-class Status(object):
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class Status(Resource):
     """
-    Retrieve the current status of all components.
+    Endpoint for status requests
     """
 
-    __version__ = "0.1.0"
+    __urls__ = ("/status", "/status/", "/status/<string:component_id>")
 
-    def get_status(self, ctx, args):
-        return {"status": "Running"}
+    def get(self, component_id=None):
+        """Retrieve status of all components
 
+        :return: {
+          "orchestrator": {
+            "status": "Running"
+          },
+          "security_router": {
+            "status": "Running"
+          }
+        }
+        """
+        raise NotImplemented
 
-class Logs(object):
+
+class Logs(Resource):
     """
-    Retrieve the current status of all components.
+    Endpoint for logs requests
     """
 
-    __version__ = "0.1.0"
+    __urls__ = ("/logs", "/logs/", "/logs/<string:component_id>")
+
+    def get(self, component_id=None):
+        """Get logs from the Moon platform
+
+        :param component_id: the ID of the component your are looking for (optional)
+        :return: [
+            "2015-04-15-13:45:20
+            "2015-04-15-13:45:21
+            "2015-04-15-13:45:22
+            "2015-04-15-13:45:23
+        ]
+        """
+        filter_str = request.args.get('filter', '')
+        from_str = request.args.get('from', '')
+        to_str = request.args.get('to', '')
+        event_number = request.args.get('event_number', '')
+        try:
+            event_number = int(event_number)
+        except ValueError:
+            event_number = None
+        args = dict()
+        args["filter"] = filter_str
+        args["from"] = from_str
+        args["to"] = to_str
+        args["event_number"] = event_number
+
+        raise NotImplemented
+
+
+class API(Resource):
+    """
+    Endpoint for API requests
+    """
 
-    def get_logs(self, ctx, args):
-        return {"error": "NotImplemented"}
+    __urls__ = (
+        "/api",
+        "/api/",
+        "/api/<string:group_id>",
+        "/api/<string:group_id>/",
+        "/api/<string:group_id>/<string:endpoint_id>")
 
+    @check_auth
+    def get(self, group_id="", endpoint_id="", user_id=""):
+        """Retrieve all API endpoints or a specific endpoint if endpoint_id is given
 
+        :param group_id: the name of one existing group (ie generic, ...)
+        :param endpoint_id: the name of one existing component (ie Logs, Status, ...)
+        :return: {
+            "group_name": {
+                "endpoint_name": {
+                    "description": "a description",
+                    "methods": {
+                        "get": "description of the HTTP method"
+                    },
+                    "urls": ('/api', '/api/', '/api/<string:endpoint_id>')
+                }
+        }
+        """
+        __methods = ("get", "post", "put", "delete", "options", "patch")
+        api_list = filter(lambda x: "__" not in x, dir(moon_manager.api))
+        api_desc = dict()
+        for api_name in api_list:
+            api_desc[api_name] = {}
+            group_api_obj = eval("moon_interface.api.{}".format(api_name))
+            api_desc[api_name]["description"] = group_api_obj.__doc__
+            if "__version__" in dir(group_api_obj):
+                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_interface.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_interface.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:
+            if endpoint_id in api_desc[group_id]:
+                return {group_id: {endpoint_id: api_desc[group_id][endpoint_id]}}
+            elif len(endpoint_id) > 0:
+                LOG.error("Unknown endpoint_id {}".format(endpoint_id))
+                return {"error": "Unknown endpoint_id {}".format(endpoint_id)}
+            return {group_id: api_desc[group_id]}
+        return api_desc
diff --git a/moonv4/moon_manager/moon_manager/api/master.py b/moonv4/moon_manager/moon_manager/api/master.py
deleted file mode 100644 (file)
index 6c1796a..0000000
+++ /dev/null
@@ -1,345 +0,0 @@
-# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
-# This software is distributed under the terms and conditions of the 'Apache-2.0'
-# license which can be found in the file 'LICENSE' in this package distribution
-# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
-
-from oslo_log import log as logging
-from moon_utilities.security_functions import call, notify
-from moon_db.core import PDPManager, PolicyManager, ModelManager
-
-LOG = logging.getLogger(__name__)
-
-
-class Master(object):
-    """
-    Retrieve the current status of all components.
-    """
-
-    __version__ = "0.1.0"
-    __policies = None
-    __policy_ids = []
-    __models = None
-    __model_ids = []
-    __meta_rules = None
-    __meta_rule_ids = []
-
-    @property
-    def policies(self):
-        if not self.__policies:
-            self.__policies = {}
-            if self.__policy_ids:
-                for policy_id in self.__policy_ids:
-                    self.__policies.update(call("moon_manager",
-                                                method="get_policies",
-                                                ctx={
-                                                    "id": policy_id,
-                                                    "call_master": True,
-                                                    "user_id": "admin"
-                                                },
-                                                args={})["policies"])
-            else:
-                self.__policies = call("moon_manager",
-                                       method="get_policies",
-                                       ctx={
-                                           "id": None,
-                                           "call_master": True,
-                                           "user_id": "admin"
-                                       },
-                                       args={})["policies"]
-        LOG.info("__get_policies={}".format(self.__policies))
-        return self.__policies
-
-    @property
-    def models(self):
-        if not self.__models:
-            self.__models = {}
-            if self.__model_ids:
-                for model_id in self.__model_ids:
-                    self.__models.update(call("moon_manager",
-                                              method="get_models",
-                                              ctx={
-                                                  "id": model_id,
-                                                  "call_master": True,
-                                                  "user_id": "admin"
-                                              },
-                                              args={})["models"])
-            else:
-                self.__models = call("moon_manager",
-                                     method="get_models",
-                                     ctx={
-                                         "id": None,
-                                         "call_master": True,
-                                         "user_id": "admin"
-                                     },
-                                     args={})["models"]
-        LOG.info("__get_models={}".format(self.__models))
-        return self.__models
-
-    @property
-    def meta_rules(self):
-        if not self.__meta_rules:
-            self.__meta_rules = {}
-            if self.__meta_rule_ids:
-                for meta_rule_id in self.__meta_rule_ids:
-                    self.__meta_rules.update(call("moon_manager",
-                                                  method="get_meta_rules",
-                                                  ctx={
-                                                      "meta_rule_id": meta_rule_id,
-                                                      "call_master": True,
-                                                      "user_id": "admin"
-                                                  },
-                                                  args={})["meta_rules"])
-            else:
-                self.__meta_rules = call("moon_manager",
-                                         method="get_meta_rules",
-                                         ctx={
-                                             "meta_rule_id": None,
-                                             "call_master": True,
-                                             "user_id": "admin"
-                                         },
-                                         args={})["meta_rules"]
-        LOG.info("__get_meta_rules={}".format(self.__meta_rules))
-        return self.__meta_rules
-
-    def __add_meta_data(self):
-        subject_categories = ModelManager.get_subject_categories("admin")
-        object_categories = ModelManager.get_object_categories("admin")
-        action_categories = ModelManager.get_action_categories("admin")
-        for meta_rule_id, meta_rule_value in self.meta_rules.items():
-            for _scat in meta_rule_value['subject_categories']:
-                if _scat not in subject_categories:
-                    master_category = call("moon_manager", method="get_subject_categories",
-                                           ctx={
-                                               "user_id": "admin",
-                                               "call_master": True,
-                                               "id": None,
-                                           },
-                                           args={"category_id": _scat})["subject_categories"]
-                    ModelManager.add_subject_category("admin", _scat, master_category[_scat])
-            for _ocat in meta_rule_value['object_categories']:
-                if _ocat not in object_categories:
-                    master_category = call("moon_manager", method="get_object_categories",
-                                           ctx={
-                                               "user_id": "admin",
-                                               "call_master": True,
-                                               "id": None,
-                                           },
-                                           args={"category_id": _ocat})["object_categories"]
-                    LOG.info("Add scat {} {}".format(_ocat, master_category[_ocat]))
-                    ModelManager.add_object_category("admin", _ocat, master_category[_ocat])
-            for _acat in meta_rule_value['action_categories']:
-                if _acat not in action_categories:
-                    master_category = call("moon_manager", method="get_action_categories",
-                                           ctx={
-                                               "user_id": "admin",
-                                               "call_master": True,
-                                               "id": None,
-                                           },
-                                           args={"category_id": _acat})["action_categories"]
-                    LOG.info("Add scat {} {}".format(_acat, master_category[_acat]))
-                    ModelManager.add_action_category("admin", _acat, master_category[_acat])
-
-    def __add_meta_rule(self):
-        meta_rules = ModelManager.get_meta_rules("admin")
-        for uuid, value in self.meta_rules.items():
-            if uuid not in meta_rules:
-                ModelManager.add_meta_rule("admin", uuid, value=value)
-
-    def __add_perimeter(self, subject_name=None, object_name=None):
-        for policy_id in self.policies:
-            subjects = call("moon_manager", method="get_subjects",
-                            ctx={
-                                "user_id": "admin",
-                                "call_master": True,
-                                "id": policy_id,
-                            },
-                            args={"perimeter_id": None, "perimeter_name": subject_name})["subjects"]
-            for subject_id, subject_value in subjects.items():
-                # FIXME (asteroide): if a subject with the same name had been already created before
-                #                    it will not have the same ID as the subject in master
-                PolicyManager.add_subject("admin", policy_id=policy_id, perimeter_id=subject_id, value=subject_value)
-        for policy_id in self.policies:
-            objects = call("moon_manager", method="get_objects",
-                           ctx={
-                               "user_id": "admin",
-                               "call_master": True,
-                               "id": policy_id,
-                           },
-                           args={"perimeter_id": None, "perimeter_name": object_name})["objects"]
-            for object_id, object_value in objects.items():
-                # FIXME (asteroide): if a object with the same name had been already created before
-                #                    it will not have the same ID as the object in master
-                PolicyManager.add_object("admin", policy_id=policy_id, perimeter_id=object_id, value=object_value)
-        for policy_id in self.policies:
-            actions = call("moon_manager", method="get_actions",
-                           ctx={
-                               "user_id": "admin",
-                               "call_master": True,
-                               "id": policy_id,
-                           },
-                           args={"perimeter_id": None})["actions"]
-            for action_id, action_value in actions.items():
-                # FIXME (asteroide): if a action with the same name had been already created before
-                #                    it will not have the same ID as the action in master
-                PolicyManager.add_action("admin", policy_id=policy_id, perimeter_id=action_id, value=action_value)
-
-    def __add_data(self):
-        subject_categories = ModelManager.get_subject_categories("admin")
-        object_categories = ModelManager.get_object_categories("admin")
-        action_categories = ModelManager.get_action_categories("admin")
-        for policy_id in self.policies:
-            for category in subject_categories.keys():
-                subject_data = call("moon_manager", method="get_subject_data",
-                                    ctx={
-                                        "user_id": "admin",
-                                        "call_master": True,
-                                        "id": policy_id,
-                                        "category_id": category
-                                    },
-                                    args={"data_id": None})["subject_data"]
-                if not subject_data:
-                    continue
-                for data in subject_data:
-                    PolicyManager.set_subject_data("admin", policy_id=policy_id,
-                                                   category_id=data['category_id'], value=data)
-            for category in object_categories:
-                object_data = call("moon_manager", method="get_object_data",
-                                   ctx={
-                                       "user_id": "admin",
-                                       "call_master": True,
-                                       "id": policy_id,
-                                       "category_id": category
-                                   },
-                                   args={"data_id": None})["object_data"]
-                if not object_data:
-                    continue
-                for data in object_data:
-                    PolicyManager.add_object_data("admin", policy_id=policy_id,
-                                                  category_id=data['category_id'], value=data)
-            for category in action_categories:
-                action_data = call("moon_manager", method="get_action_data",
-                                   ctx={
-                                       "user_id": "admin",
-                                       "call_master": True,
-                                       "id": policy_id,
-                                       "category_id": category
-                                   },
-                                   args={"data_id": None})["action_data"]
-                if not action_data:
-                    continue
-                for data in action_data:
-                    PolicyManager.add_action_data("admin", policy_id=policy_id,
-                                                  category_id=data['category_id'], value=data)
-
-    def __add_assignments(self, subject_name=None, object_name=None):
-        for policy_id in self.policies:
-            assignments = call("moon_manager", method="get_subject_assignments",
-                               ctx={
-                                   "user_id": "admin",
-                                   "call_master": True,
-                                   "id": policy_id,
-                                   "perimeter_id": None,
-                                   "perimeter_name": subject_name,
-                                   "category_id": None,
-                               },
-                               args={})["subject_assignments"]
-            for assignment_id, assignment_value in assignments.items():
-                _subject_id = assignment_value['subject_id']
-                _category_id = assignment_value['category_id']
-                for _data_id in assignment_value['assignments']:
-                    PolicyManager.add_subject_assignment("admin", policy_id=policy_id,
-                                                         subject_id=_subject_id, category_id=_category_id,
-                                                         data_id=_data_id)
-            assignments = call("moon_manager", method="get_object_assignments",
-                               ctx={
-                                   "user_id": "admin",
-                                   "call_master": True,
-                                   "id": policy_id,
-                                   "perimeter_id": None,
-                                   "perimeter_name": object_name,
-                                   "category_id": None,
-                               },
-                               args={})["object_assignments"]
-            for assignment_id, assignment_value in assignments.items():
-                _object_id = assignment_value['object_id']
-                _category_id = assignment_value['category_id']
-                for _data_id in assignment_value['assignments']:
-                    PolicyManager.add_object_assignment("admin", policy_id=policy_id,
-                                                        object_id=_object_id, category_id=_category_id,
-                                                        data_id=_data_id)
-            assignments = call("moon_manager", method="get_action_assignments",
-                               ctx={
-                                   "user_id": "admin",
-                                   "call_master": True,
-                                   "id": policy_id,
-                                   "perimeter_id": None,
-                                   "category_id": None,
-                               },
-                               args={})["action_assignments"]
-            for assignment_id, assignment_value in assignments.items():
-                _action_id = assignment_value['action_id']
-                _category_id = assignment_value['category_id']
-                for _data_id in assignment_value['assignments']:
-                    PolicyManager.add_action_assignment("admin", policy_id=policy_id,
-                                                        action_id=_action_id, category_id=_category_id,
-                                                        data_id=_data_id)
-
-    def __add_rules(self):
-        for policy_id in self.policies:
-            _rules = call("moon_manager", method="get_rules",
-                          ctx={
-                              "user_id": "admin",
-                              "call_master": True,
-                              "id": policy_id,
-                              "rule_id": None
-                          },
-                          args={})["rules"]
-            for rule in _rules["rules"]:
-                LOG.info("__add_rules {}".format(rule))
-                if rule["meta_rule_id"] in self.__meta_rule_ids:
-                    PolicyManager.add_rule("admin",
-                                           policy_id=policy_id,
-                                           meta_rule_id=rule["meta_rule_id"],
-                                           value=rule)
-
-    def update_from_master(self, ctx, args):
-        LOG.info("update_from_master {}".format(ctx))
-        if "security_pipeline" in ctx:
-            self.__policy_ids = ctx["security_pipeline"]
-
-            for policy_id, policy_value in self.policies.items():
-                self.__model_ids.append(policy_value["model_id"])
-
-            for model_id, model_value in self.models.items():
-                self.__meta_rule_ids.extend(model_value['meta_rules'])
-
-            self.__add_meta_data()
-
-            self.__add_meta_rule()
-
-            for policy_id in ctx["security_pipeline"]:
-                if policy_id in self.policies:
-                    res = PolicyManager.add_policy("admin", policy_id, self.__policies[policy_id])
-
-        self.__add_perimeter(subject_name=ctx.get("subject_name"), object_name=ctx.get("object_name"))
-
-        self.__add_data()
-
-        self.__add_assignments(subject_name=ctx.get("subject_name"), object_name=ctx.get("object_name"))
-
-        self.__add_rules()
-
-        models = ModelManager.get_models("admin")
-        for model_id, model_value in self.models.items():
-            if model_id not in models:
-                ModelManager.add_model("admin", model_id, model_value)
-
-        if args:
-            pdp = PDPManager.add_pdp(user_id="admin", pdp_id=ctx["pdp_id"], value=args)
-            if "error" in pdp:
-                LOG.error("Error when adding PDP from master {}".format(pdp))
-                return False
-            call("orchestrator", method="add_container",
-                 ctx={"id": ctx.get("id"), "pipeline": ctx['security_pipeline']})
-        return True
-
diff --git a/moonv4/moon_manager/moon_manager/api/meta_data.py b/moonv4/moon_manager/moon_manager/api/meta_data.py
new file mode 100644 (file)
index 0000000..0f9078e
--- /dev/null
@@ -0,0 +1,258 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Meta Data are elements used to create Meta data (skeleton of security policies)
+
+"""
+
+from flask import request
+from flask_restful import Resource
+from oslo_log import log as logging
+from moon_utilities.security_functions import check_auth
+from moon_db.core import ModelManager
+
+__version__ = "0.2.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class SubjectCategories(Resource):
+    """
+    Endpoint for subject categories requests
+    """
+
+    __urls__ = (
+        "/subject_categories",
+        "/subject_categories/",
+        "/subject_categories/<string:category_id>",
+    )
+
+    @check_auth
+    def get(self, category_id=None, user_id=None):
+        """Retrieve all subject categories or a specific one
+
+        :param category_id: uuid of the subject category
+        :param user_id: user ID who do the request
+        :return: {
+            "subject_category_id": {
+                "name": "name of the category",
+                "description": "description of the category"
+            }
+        }
+        :internal_api: get_subject_categories
+        """
+        try:
+            data = ModelManager.get_subject_categories(user_id=user_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subject_categories": data}
+
+    @check_auth
+    def post(self, category_id=None, user_id=None):
+        """Create or update a subject category.
+
+        :param category_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the category",
+            "description": "description of the category"
+        }
+        :return: {
+            "subject_category_id": {
+                "name": "name of the category",
+                "description": "description of the category"
+            }
+        }
+        :internal_api: add_subject_category
+        """
+        try:
+            data = ModelManager.add_subject_category(user_id=user_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subject_categories": data}
+
+    @check_auth
+    def delete(self, category_id=None, user_id=None):
+        """Delete a subject category
+
+        :param category_id: uuid of the subject category to delete
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_subject_category
+        """
+        try:
+            data = ModelManager.delete_subject_category(user_id=user_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class ObjectCategories(Resource):
+    """
+    Endpoint for object categories requests
+    """
+
+    __urls__ = (
+        "/object_categories",
+        "/object_categories/",
+        "/object_categories/<string:category_id>",
+    )
+
+    @check_auth
+    def get(self, category_id=None, user_id=None):
+        """Retrieve all object categories or a specific one
+
+        :param category_id: uuid of the object category
+        :param user_id: user ID who do the request
+        :return: {
+            "object_category_id": {
+                "name": "name of the category",
+                "description": "description of the category"
+            }
+        }
+        :internal_api: get_object_categories
+        """
+        try:
+            data = ModelManager.get_object_categories(user_id=user_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"object_categories": data}
+
+    @check_auth
+    def post(self, category_id=None, user_id=None):
+        """Create or update a object category.
+
+        :param category_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the category",
+            "description": "description of the category"
+        }
+        :return: {
+            "object_category_id": {
+                "name": "name of the category",
+                "description": "description of the category"
+            }
+        }
+        :internal_api: add_object_category
+        """
+        try:
+            data = ModelManager.add_object_category(user_id=user_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"object_categories": data}
+
+    @check_auth
+    def delete(self, category_id=None, user_id=None):
+        """Delete an object category
+
+        :param category_id: uuid of the object category to delete
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_object_category
+        """
+        try:
+            data = ModelManager.delete_object_category(user_id=user_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class ActionCategories(Resource):
+    """
+    Endpoint for action categories requests
+    """
+
+    __urls__ = (
+        "/action_categories",
+        "/action_categories/",
+        "/action_categories/<string:category_id>",
+    )
+
+    @check_auth
+    def get(self, category_id=None, user_id=None):
+        """Retrieve all action categories or a specific one
+
+        :param category_id: uuid of the action category
+        :param user_id: user ID who do the request
+        :return: {
+            "action_category_id": {
+                "name": "name of the category",
+                "description": "description of the category"
+            }
+        }
+        :internal_api: get_action_categories
+        """
+        try:
+            data = ModelManager.get_action_categories(user_id=user_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"action_categories": data}
+
+    @check_auth
+    def post(self, category_id=None, user_id=None):
+        """Create or update an action category.
+
+        :param category_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the category",
+            "description": "description of the category"
+        }
+        :return: {
+            "action_category_id": {
+                "name": "name of the category",
+                "description": "description of the category"
+            }
+        }
+        :internal_api: add_action_category
+        """
+        try:
+            data = ModelManager.add_action_category(user_id=user_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"action_categories": data}
+
+    @check_auth
+    def delete(self, category_id=None, user_id=None):
+        """Delete an action
+
+        :param category_id: uuid of the action category to delete
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_action_category
+        """
+        try:
+            data = ModelManager.delete_action_category(user_id=user_id, category_id=category_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
diff --git a/moonv4/moon_manager/moon_manager/api/meta_rules.py b/moonv4/moon_manager/moon_manager/api/meta_rules.py
new file mode 100644 (file)
index 0000000..dc3ea0d
--- /dev/null
@@ -0,0 +1,153 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Meta rules are skeleton for security policies
+
+"""
+
+from flask import request
+from flask_restful import Resource
+from oslo_log import log as logging
+from moon_utilities.security_functions import check_auth
+from moon_db.core import ModelManager
+
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class MetaRules(Resource):
+    """
+    Endpoint for meta rules requests
+    """
+
+    __urls__ = ("/meta_rules",
+                "/meta_rules/",
+                "/meta_rules/<string:meta_rule_id>",
+                "/meta_rules/<string:meta_rule_id>/")
+
+    @check_auth
+    def get(self, meta_rule_id=None, user_id=None):
+        """Retrieve all sub meta rules
+
+        :param meta_rule_id: Meta rule algorithm ID
+        :param user_id: user ID who do the request
+        :return: {
+            "meta_rules": {
+                "meta_rule_id1": {
+                    "name": "name of the meta rule",
+                    "algorithm": "name of the meta rule algorithm",
+                    "subject_categories": ["subject_category_id1", "subject_category_id2"],
+                    "object_categories": ["object_category_id1"],
+                    "action_categories": ["action_category_id1"]
+                },
+            }
+        }
+        :internal_api: get_meta_rules
+        """
+        try:
+            data = ModelManager.get_meta_rules(user_id=user_id, meta_rule_id=meta_rule_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"meta_rules": data}
+
+    @check_auth
+    def post(self, meta_rule_id=None, user_id=None):
+        """Add a meta rule
+
+        :param meta_rule_id: Meta rule ID
+        :param user_id: user ID who do the request
+        :request body: post = {
+            "name": "name of the meta rule",
+            "subject_categories": ["subject_category_id1", "subject_category_id2"],
+            "object_categories": ["object_category_id1"],
+            "action_categories": ["action_category_id1"]
+        }
+        :return: {
+            "meta_rules": {
+                "meta_rule_id1": {
+                    "name": "name of the meta rule",
+                    "subject_categories": ["subject_category_id1", "subject_category_id2"],
+                    "object_categories": ["object_category_id1"],
+                    "action_categories": ["action_category_id1"]
+                },
+            }
+        }
+        :internal_api: add_meta_rules
+        """
+        try:
+            data = ModelManager.add_meta_rule(user_id=user_id, meta_rule_id=None, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"meta_rules": data}
+
+    @check_auth
+    def patch(self, meta_rule_id=None, user_id=None):
+        """Update a meta rule
+
+        :param meta_rule_id: Meta rule ID
+        :param user_id: user ID who do the request
+        :request body: patch = {
+            "name": "name of the meta rule",
+            "subject_categories": ["subject_category_id1", "subject_category_id2"],
+            "object_categories": ["object_category_id1"],
+            "action_categories": ["action_category_id1"]
+        }
+        :return: {
+            "meta_rules": {
+                "meta_rule_id1": {
+                    "name": "name of the meta rule",
+                    "subject_categories": ["subject_category_id1", "subject_category_id2"],
+                    "object_categories": ["object_category_id1"],
+                    "action_categories": ["action_category_id1"]
+                },
+            }
+        }
+        :internal_api: set_meta_rules
+        """
+        try:
+            data = ModelManager.set_meta_rule(user_id=user_id, meta_rule_id=meta_rule_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"meta_rules": data}
+
+    @check_auth
+    def delete(self, meta_rule_id=None, user_id=None):
+        """Delete a meta rule
+
+        :param meta_rule_id: Meta rule ID
+        :param user_id: user ID who do the request
+        :request body: delete = {
+            "name": "name of the meta rule",
+            "subject_categories": ["subject_category_id1", "subject_category_id2"],
+            "object_categories": ["object_category_id1"],
+            "action_categories": ["action_category_id1"]
+        }
+        :return: {
+            "meta_rules": {
+                "meta_rule_id1": {
+                    "name": "name of the meta rule",
+                    "subject_categories": ["subject_category_id1", "subject_category_id2"],
+                    "object_categories": ["object_category_id1"],
+                    "action_categories": ["action_category_id1"]
+                },
+            }
+        }
+        :internal_api: delete_meta_rules
+        """
+        try:
+            data = ModelManager.delete_meta_rule(user_id=user_id, meta_rule_id=meta_rule_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
index 56695c1..cec899f 100644 (file)
 # This software is distributed under the terms and conditions of the 'Apache-2.0'
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Models aggregate multiple meta rules
+"""
 
+from flask import request
+from flask_restful import Resource
 from oslo_log import log as logging
-from oslo_config import cfg
+from moon_utilities.security_functions import check_auth
 from moon_db.core import ModelManager
 
-LOG = logging.getLogger(__name__)
-CONF = cfg.CONF
+__version__ = "0.1.0"
 
+LOG = logging.getLogger("moon.manager.api." + __name__)
 
-class Models(object):
 
-    def __init__(self):
-        self.manager = ModelManager
+class Models(Resource):
+    """
+    Endpoint for model requests
+    """
 
-    def get_models(self, ctx, args):
-        try:
-            data = self.manager.get_models(user_id=ctx["user_id"], model_id=ctx.get("id"))
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"models": data}
+    __urls__ = (
+        "/models",
+        "/models/",
+        "/models/<string:uuid>",
+        "/models/<string:uuid>/",
+    )
 
-    def add_model(self, ctx, args):
-        try:
-            data = self.manager.add_model(user_id=ctx["user_id"], model_id=ctx.get("id"), value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"models": data}
+    @check_auth
+    def get(self, uuid=None, user_id=None):
+        """Retrieve all models
 
-    def delete_model(self, ctx, args):
+        :param uuid: uuid of the model
+        :param user_id: user ID who do the request
+        :return: {
+            "model_id1": {
+                "name": "...",
+                "description": "...",
+                "meta_rules": ["meta_rule_id1", ]
+            }
+        }
+        :internal_api: get_models
+        """
         try:
-            data = self.manager.delete_model(user_id=ctx["user_id"], model_id=ctx["id"])
+            data = ModelManager.get_models(user_id=user_id, model_id=uuid)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def update_model(self, ctx, args):
-        try:
-            data = self.manager.update_model(user_id=ctx["user_id"], model_id=ctx["id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"models": data}
 
+    @check_auth
+    def post(self, uuid=None, user_id=None):
+        """Create model.
 
-class MetaRules(object):
-
-    def __init__(self):
-        self.manager = ModelManager
-
-    def add_meta_rules(self, ctx, args):
+        :param uuid: uuid of the model (not used here)
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "...",
+            "description": "...",
+            "meta_rules": ["meta_rule_id1", ]
+        }
+        :return: {
+            "model_id1": {
+                "name": "...",
+                "description": "...",
+                "meta_rules": ["meta_rule_id1", ]
+            }
+        }
+        :internal_api: add_model
+        """
         try:
-            data = self.manager.add_meta_rule(user_id=ctx["user_id"], meta_rule_id=None, value=args)
+            data = ModelManager.add_model(user_id=user_id, model_id=uuid, value=request.json)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"meta_rules": data}
-
-    def delete_meta_rules(self, ctx, args):
-        try:
-            data = self.manager.delete_meta_rule(user_id=ctx["user_id"], meta_rule_id=ctx["meta_rule_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_meta_rules(self, ctx, args):
-        try:
-            data = self.manager.get_meta_rules(user_id=ctx["user_id"], meta_rule_id=ctx["meta_rule_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"meta_rules": data}
-
-    def set_meta_rules(self, ctx, args):
-        try:
-            data = self.manager.set_meta_rule(user_id=ctx["user_id"], meta_rule_id=ctx["meta_rule_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"meta_rules": data}
-
-
-class MetaData(object):
-
-    def __init__(self):
-        self.manager = ModelManager
-
-    def get_subject_categories(self, ctx, args):
-        try:
-            data = self.manager.get_subject_categories(user_id=ctx["user_id"], category_id=args["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subject_categories": data}
-
-    def set_subject_category(self, ctx, args):
-        try:
-            data = self.manager.add_subject_category(user_id=ctx["user_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subject_categories": data}
-
-    def delete_subject_category(self, ctx, args):
-        try:
-            data = self.manager.delete_subject_category(user_id=ctx["user_id"], category_id=args["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_object_categories(self, ctx, args):
-        try:
-            data = self.manager.get_object_categories(user_id=ctx["user_id"], category_id=args["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"object_categories": data}
+                    "error": str(e)}
+        return {"models": data}
 
-    def set_object_category(self, ctx, args):
-        try:
-            data = self.manager.add_object_category(user_id=ctx["user_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"object_categories": data}
+    @check_auth
+    def delete(self, uuid=None, user_id=None):
+        """Delete a model
 
-    def delete_object_category(self, ctx, args):
+        :param uuid: uuid of the model to delete
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_model
+        """
         try:
-            data = self.manager.delete_object_category(user_id=ctx["user_id"], category_id=args["category_id"])
+            data = ModelManager.delete_model(user_id=user_id, model_id=uuid)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"result": True}
 
-    def get_action_categories(self, ctx, args):
-        try:
-            data = self.manager.get_action_categories(user_id=ctx["user_id"], category_id=args["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"action_categories": data}
+    @check_auth
+    def patch(self, uuid=None, user_id=None):
+        """Update a model
 
-    def set_action_category(self, ctx, args):
+        :param uuid: uuid of the model to update
+        :param user_id: user ID who do the request
+        :return: {
+            "model_id1": {
+                "name": "...",
+                "description": "...",
+                "meta_rules": ["meta_rule_id1", ]
+            }
+        }
+        :internal_api: update_model
+        """
         try:
-            data = self.manager.add_action_category(user_id=ctx["user_id"], value=args)
+            data = ModelManager.update_model(user_id=user_id, model_id=uuid, value=request.json)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"action_categories": data}
+                    "error": str(e)}
+        return {"models": data}
 
-    def delete_action_category(self, ctx, args):
-        try:
-            data = self.manager.delete_action_category(user_id=ctx["user_id"], category_id=args["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
index 2250462..15f4988 100644 (file)
 # This software is distributed under the terms and conditions of the 'Apache-2.0'
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+PDP are Policy Decision Point.
 
-import os
-import json
-import copy
-from uuid import uuid4
+"""
+
+from flask import request
+from flask_restful import Resource
 from oslo_log import log as logging
-from oslo_config import cfg
-from moon_utilities import exceptions
+from moon_utilities.security_functions import check_auth
 from moon_db.core import PDPManager
-from moon_utilities.misc import get_uuid_from_name
-from moon_utilities.security_functions import call
 
-LOG = logging.getLogger(__name__)
-CONF = cfg.CONF
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+def add_container(uuid, pipeline):
+    # TODO: to implement
+    LOG.warning("Add container not implemented!")
+    LOG.info(uuid)
+    LOG.info(pipeline)
+
 
+class PDP(Resource):
+    """
+    Endpoint for pdp requests
+    """
 
-class PDP(object):
+    __urls__ = (
+        "/pdp",
+        "/pdp/",
+        "/pdp/<string:uuid>",
+        "/pdp/<string:uuid>/",
+    )
 
-    def __init__(self):
-        self.manager = PDPManager
+    @check_auth
+    def get(self, uuid=None, user_id=None):
+        """Retrieve all pdp
 
-    def get_pdp(self, ctx, args=None):
+        :param uuid: uuid of the pdp
+        :param user_id: user ID who do the request
+        :return: {
+            "pdp_id1": {
+                "name": "...",
+                "security_pipeline": [...],
+                "keystone_project_id": "keystone_project_id1",
+                "description": "...",
+            }
+        }
+        :internal_api: get_pdp
+        """
         try:
-            data = self.manager.get_pdp(user_id=ctx["user_id"], pdp_id=ctx.get("id"))
+            data = PDPManager.get_pdp(user_id=user_id, pdp_id=uuid)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"pdps": data}
 
-    def add_pdp(self, ctx, args):
+    @check_auth
+    def post(self, uuid=None, user_id=None):
+        """Create pdp.
+
+        :param uuid: uuid of the pdp (not used here)
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "...",
+            "security_pipeline": [...],
+            "keystone_project_id": "keystone_project_id1",
+            "description": "...",
+        }
+        :return: {
+            "pdp_id1": {
+                "name": "...",
+                "security_pipeline": [...],
+                "keystone_project_id": "keystone_project_id1",
+                "description": "...",
+            }
+        }
+        :internal_api: add_pdp
+        """
         try:
-            data = self.manager.add_pdp(user_id=ctx["user_id"], pdp_id=None, value=args)
+            data = PDPManager.add_pdp(user_id=user_id, pdp_id=None, value=request.json)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"pdps": data}
 
-    def delete_pdp(self, ctx, args):
+    @check_auth
+    def delete(self, uuid=None, user_id=None):
+        """Delete a pdp
+
+        :param uuid: uuid of the pdp to delete
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_pdp
+        """
         try:
-            data = self.manager.delete_pdp(user_id=ctx["user_id"], pdp_id=ctx.get("id"))
+            data = PDPManager.delete_pdp(user_id=user_id, pdp_id=uuid)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"result": True}
 
-    def update_pdp(self, ctx, args):
+    @check_auth
+    def patch(self, uuid=None, user_id=None):
+        """Update a pdp
+
+        :param uuid: uuid of the pdp to update
+        :param user_id: user ID who do the request
+        :return: {
+            "pdp_id1": {
+                "name": "...",
+                "security_pipeline": [...],
+                "keystone_project_id": "keystone_project_id1",
+                "description": "...",
+            }
+        }
+        :internal_api: update_pdp
+        """
         try:
-            data = self.manager.update_pdp(user_id=ctx["user_id"], pdp_id=ctx.get("id"), value=args)
-            call("orchestrator", method="add_container",
-                 ctx={"id": ctx.get("id"), "pipeline": data[ctx.get("id")]['security_pipeline']})
+            data = PDPManager.update_pdp(user_id=user_id, pdp_id=uuid, value=request.json)
+            add_container(uuid=uuid, pipeline=data[uuid]['security_pipeline'])
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"pdps": data}
 
-
diff --git a/moonv4/moon_manager/moon_manager/api/perimeter.py b/moonv4/moon_manager/moon_manager/api/perimeter.py
new file mode 100644 (file)
index 0000000..cc2c056
--- /dev/null
@@ -0,0 +1,430 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+* Subjects are the source of an action on an object (examples : users, virtual machines)
+* Objects are the destination of an action (examples virtual machines, virtual Routers)
+* Actions are what subject wants to do on an object
+"""
+
+from flask import request
+from flask_restful import Resource
+from oslo_log import log as logging
+from moon_utilities.security_functions import check_auth
+from moon_db.core import PolicyManager
+
+__version__ = "0.2.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class Subjects(Resource):
+    """
+    Endpoint for subjects requests
+    """
+
+    __urls__ = (
+        "/subjects",
+        "/subjects/",
+        "/subjects/<string:perimeter_id>",
+        "/policies/<string:uuid>/subjects",
+        "/policies/<string:uuid>/subjects/",
+        "/policies/<string:uuid>/subjects/<string:perimeter_id>",
+    )
+
+    @check_auth
+    def get(self, uuid=None, perimeter_id=None, user_id=None):
+        """Retrieve all subjects or a specific one if perimeter_id is given for a given policy
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the subject
+        :param user_id: user ID who do the request
+        :return: {
+                "subject_id": {
+                    "name": "name of the subject",
+                    "keystone_id": "keystone id of the subject",
+                    "description": "a description"
+            }
+        }
+        :internal_api: get_subjects
+        """
+        try:
+            data = PolicyManager.get_subjects(
+                user_id=user_id,
+                policy_id=uuid,
+                perimeter_id=perimeter_id
+            )
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subjects": data}
+
+    @check_auth
+    def post(self, uuid=None, perimeter_id=None, user_id=None):
+        """Create or update a subject.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the subject",
+            "description": "description of the subject",
+            "password": "password for the subject",
+            "email": "email address of the subject"
+        }
+        :return: {
+                "subject_id": {
+                    "name": "name of the subject",
+                    "keystone_id": "keystone id of the subject",
+                    "description": "description of the subject",
+                    "password": "password for the subject",
+                    "email": "email address of the subject"
+            }
+        }
+        :internal_api: set_subject
+        """
+        try:
+            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)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subjects": data}
+
+    @check_auth
+    def patch(self, uuid=None, perimeter_id=None, user_id=None):
+        """Create or update a subject.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the subject",
+            "description": "description of the subject",
+            "password": "password for the subject",
+            "email": "email address of the subject"
+        }
+        :return: {
+                "subject_id": {
+                    "name": "name of the subject",
+                    "keystone_id": "keystone id of the subject",
+                    "description": "description of the subject",
+                    "password": "password for the subject",
+                    "email": "email address of the subject"
+            }
+        }
+        :internal_api: set_subject
+        """
+        try:
+            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)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"subjects": data}
+
+    @check_auth
+    def delete(self, uuid=None, perimeter_id=None, user_id=None):
+        """Delete a subject for a given policy
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the subject
+        :param user_id: user ID who do the request
+        :return: {
+                "subject_id": {
+                    "name": "name of the subject",
+                    "keystone_id": "keystone id of the subject",
+                    "description": "description of the subject",
+                    "password": "password for the subject",
+                    "email": "email address of the subject"
+            }
+        }
+        :internal_api: delete_subject
+        """
+        try:
+            data = PolicyManager.delete_subject(user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class Objects(Resource):
+    """
+    Endpoint for objects requests
+    """
+
+    __urls__ = (
+        "/objects",
+        "/objects/",
+        "/objects/<string:perimeter_id>",
+        "/policies/<string:uuid>/objects",
+        "/policies/<string:uuid>/objects/",
+        "/policies/<string:uuid>/objects/<string:perimeter_id>",
+    )
+
+    @check_auth
+    def get(self, uuid=None, perimeter_id=None, user_id=None):
+        """Retrieve all objects or a specific one if perimeter_id is given for a given policy
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the object
+        :param user_id: user ID who do the request
+        :return: {
+                "object_id": {
+                    "name": "name of the object",
+                    "description": "description of the object"
+            }
+        }
+        :internal_api: get_objects
+        """
+        try:
+            data = PolicyManager.get_objects(
+                user_id=user_id,
+                policy_id=uuid,
+                perimeter_id=perimeter_id
+            )
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"objects": data}
+
+    @check_auth
+    def post(self, uuid=None, perimeter_id=None, user_id=None):
+        """Create or update a object.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "object_name": "name of the object",
+            "object_description": "description of the object"
+        }
+        :return: {
+                "object_id": {
+                    "name": "name of the object",
+                    "description": "description of the object"
+            }
+        }
+        :internal_api: set_object
+        """
+        try:
+            data = PolicyManager.get_objects(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_object(user_id=user_id, policy_id=uuid,
+                                            perimeter_id=perimeter_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"objects": data}
+
+    @check_auth
+    def patch(self, uuid=None, perimeter_id=None, user_id=None):
+        """Create or update a object.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "object_name": "name of the object",
+            "object_description": "description of the object"
+        }
+        :return: {
+                "object_id": {
+                    "name": "name of the object",
+                    "description": "description of the object"
+            }
+        }
+        :internal_api: set_object
+        """
+        try:
+            data = PolicyManager.get_objects(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_object(user_id=user_id, policy_id=uuid,
+                                            perimeter_id=perimeter_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"objects": data}
+
+    @check_auth
+    def delete(self, uuid=None, perimeter_id=None, user_id=None):
+        """Delete a object for a given policy
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the object
+        :param user_id: user ID who do the request
+        :return: {
+                "object_id": {
+                    "name": "name of the object",
+                    "description": "description of the object"
+            }
+        }
+        :internal_api: delete_object
+        """
+        try:
+            data = PolicyManager.delete_object(user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
+
+class Actions(Resource):
+    """
+    Endpoint for actions requests
+    """
+
+    __urls__ = (
+        "/actions",
+        "/actions/",
+        "/actions/<string:perimeter_id>",
+        "/policies/<string:uuid>/actions",
+        "/policies/<string:uuid>/actions/",
+        "/policies/<string:uuid>/actions/<string:perimeter_id>",
+    )
+
+    @check_auth
+    def get(self, uuid=None, perimeter_id=None, user_id=None):
+        """Retrieve all actions or a specific one if perimeter_id is given for a given policy
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the action
+        :param user_id: user ID who do the request
+        :return: {
+                "action_id": {
+                    "name": "name of the action",
+                    "description": "description of the action"
+            }
+        }
+        :internal_api: get_actions
+        """
+        try:
+            data = PolicyManager.get_actions(user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"actions": data}
+
+    @check_auth
+    def post(self, uuid=None, perimeter_id=None, user_id=None):
+        """Create or update a action.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the action",
+            "description": "description of the action"
+        }
+        :return: {
+                "action_id": {
+                    "name": "name of the action",
+                    "description": "description of the action"
+            }
+        }
+        :internal_api: set_action
+        """
+        try:
+            data = PolicyManager.get_actions(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_action(user_id=user_id, policy_id=uuid,
+                                            perimeter_id=perimeter_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"actions": data}
+
+    @check_auth
+    def patch(self, uuid=None, perimeter_id=None, user_id=None):
+        """Create or update a action.
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: must not be used here
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "name of the action",
+            "description": "description of the action"
+        }
+        :return: {
+                "action_id": {
+                    "name": "name of the action",
+                    "description": "description of the action"
+            }
+        }
+        :internal_api: set_action
+        """
+        try:
+            data = PolicyManager.get_actions(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_action(user_id=user_id, policy_id=uuid,
+                                            perimeter_id=perimeter_id, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"actions": data}
+
+    @check_auth
+    def delete(self, uuid=None, perimeter_id=None, user_id=None):
+        """Delete a action for a given policy
+
+        :param uuid: uuid of the policy
+        :param perimeter_id: uuid of the action
+        :param user_id: user ID who do the request
+        :return: {
+                "action_id": {
+                    "name": "name of the action",
+                    "description": "description of the action"
+            }
+        }
+        :internal_api: delete_action
+        """
+        try:
+            data = PolicyManager.delete_action(user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
index 65b6994..737b988 100644 (file)
 # This software is distributed under the terms and conditions of the 'Apache-2.0'
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Policies are instances of security models and implement security policies
 
+"""
+
+from flask import request
+from flask_restful import Resource
 from oslo_log import log as logging
-from oslo_config import cfg
+from moon_utilities.security_functions import check_auth
 from moon_db.core import PolicyManager
 
-LOG = logging.getLogger(__name__)
-CONF = cfg.CONF
+__version__ = "0.1.0"
 
+LOG = logging.getLogger("moon.manager.api." + __name__)
 
-class Policies(object):
 
-    def __init__(self):
-        self.manager = PolicyManager
+class Policies(Resource):
+    """
+    Endpoint for policy requests
+    """
 
-    def get_policies(self, ctx, args):
-        try:
-            data = self.manager.get_policies(user_id=ctx["user_id"], policy_id=ctx.get("id"))
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"policies": data}
+    __urls__ = (
+        "/policies",
+        "/policies/",
+        "/policies/<string:uuid>",
+        "/policies/<string:uuid>/",
+    )
 
-    def add_policy(self, ctx, args):
-        try:
-            data = self.manager.add_policy(user_id=ctx["user_id"], policy_id=ctx.get("id"), value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"policies": data}
+    @check_auth
+    def get(self, uuid=None, user_id=None):
+        """Retrieve all policies
 
-    def delete_policy(self, ctx, args):
+        :param uuid: uuid of the policy
+        :param user_id: user ID who do the request
+        :return: {
+            "policy_id1": {
+                "name": "...",
+                "model_id": "...",
+                "genre": "...",
+                "description": "...",
+            }
+        }
+        :internal_api: get_policies
+        """
         try:
-            data = self.manager.delete_policy(user_id=ctx["user_id"], policy_id=ctx["id"])
+            data = PolicyManager.get_policies(user_id=user_id, policy_id=uuid)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def update_policy(self, ctx, args):
-        try:
-            data = self.manager.update_policy(user_id=ctx["user_id"], policy_id=ctx["id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"policies": data}
 
+    @check_auth
+    def post(self, uuid=None, user_id=None):
+        """Create policy.
+
+        :param uuid: uuid of the policy (not used here)
+        :param user_id: user ID who do the request
+        :request body: {
+            "name": "...",
+            "model_id": "...",
+            "genre": "...",
+            "description": "...",
+        }
+        :return: {
+            "policy_id1": {
+                "name": "...",
+                "model_id": "...",
+                "genre": "...",
+                "description": "...",
+            }
+        }
+        :internal_api: add_policy
+        """
+        try:
+            data = PolicyManager.add_policy(user_id=user_id, policy_id=uuid, value=request.json)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"policies": data}
 
-class Perimeter(object):
-
-    def __init__(self):
-        self.manager = PolicyManager
-
-    def get_subjects(self, ctx, args):
-        try:
-            data = self.manager.get_subjects(
-                user_id=ctx["user_id"],
-                policy_id=ctx["id"],
-                perimeter_id=args['perimeter_id']
-            )
-            if not args['perimeter_id']:
-                if "perimeter_name" in args:
-                    for _data_id, _data_value in data.items():
-                        if _data_value['name'] == args['perimeter_name']:
-                            data = {_data_id: _data_value}
-                            break
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subjects": data}
-
-    def set_subject(self, ctx, args):
-        try:
-            if not ctx["perimeter_id"]:
-                data = self.manager.get_subjects(user_id=ctx["user_id"], policy_id=None)
-                if 'name' in args:
-                    for data_id, data_value in data.items():
-                        if data_value['name'] == args['name']:
-                            ctx["perimeter_id"] = data_id
-                            break
-            data = self.manager.add_subject(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                            perimeter_id=ctx["perimeter_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subjects": data}
-
-    def delete_subject(self, ctx, args):
-        try:
-            data = self.manager.delete_subject(user_id=ctx["user_id"], policy_id=ctx["id"], perimeter_id=args["perimeter_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_objects(self, ctx, args):
-        try:
-            data = self.manager.get_objects(
-                user_id=ctx["user_id"],
-                policy_id=ctx["id"],
-                perimeter_id=args['perimeter_id']
-            )
-            if not args['perimeter_id']:
-                if "perimeter_name" in args:
-                    for _data_id, _data_value in data.items():
-                        if _data_value['name'] == args['perimeter_name']:
-                            data = {_data_id: _data_value}
-                            break
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"objects": data}
-
-    def set_object(self, ctx, args):
-        try:
-            data = self.manager.get_objects(user_id=ctx["user_id"], policy_id=None)
-            if 'name' in args:
-                for data_id, data_value in data.items():
-                    if data_value['name'] == args['name']:
-                        ctx["perimeter_id"] = data_id
-                        break
-            data = self.manager.add_object(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                           perimeter_id=ctx["perimeter_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"objects": data}
-
-    def delete_object(self, ctx, args):
-        try:
-            data = self.manager.delete_object(user_id=ctx["user_id"], policy_id=ctx["id"], perimeter_id=args["perimeter_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_actions(self, ctx, args):
-        try:
-            data = self.manager.get_actions(user_id=ctx["user_id"], policy_id=ctx["id"], perimeter_id=args['perimeter_id'])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"actions": data}
-
-    def set_action(self, ctx, args):
-        try:
-            data = self.manager.get_actions(user_id=ctx["user_id"], policy_id=None)
-            if 'name' in args:
-                for data_id, data_value in data.items():
-                    if data_value['name'] == args['name']:
-                        ctx["perimeter_id"] = data_id
-                        break
-            data = self.manager.add_action(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                           perimeter_id=ctx["perimeter_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"actions": data}
-
-    def delete_action(self, ctx, args):
-        try:
-            data = self.manager.delete_action(user_id=ctx["user_id"], policy_id=ctx["id"], perimeter_id=args["perimeter_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-
-class Data(object):
-
-    def __init__(self):
-        self.manager = PolicyManager
-
-    def get_subject_data(self, ctx, args):
-        try:
-            data = self.manager.get_subject_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                 category_id=ctx["category_id"], data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subject_data": data}
-
-    def add_subject_data(self, ctx, args):
-        try:
-            data = self.manager.set_subject_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                 category_id=ctx["category_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subject_data": data}
-
-    def delete_subject_data(self, ctx, args):
-        try:
-            data = self.manager.delete_subject_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                    data_id=["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_object_data(self, ctx, args):
-        try:
-            data = self.manager.get_object_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                category_id=ctx["category_id"], data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"object_data": data}
-
-    def add_object_data(self, ctx, args):
-        try:
-            data = self.manager.add_object_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                category_id=ctx["category_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"object_data": data}
-
-    def delete_object_data(self, ctx, args):
-        try:
-            data = self.manager.delete_object_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                   data_id=["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_action_data(self, ctx, args):
-        try:
-            data = self.manager.get_action_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                category_id=ctx["category_id"], data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"action_data": data}
-
-    def add_action_data(self, ctx, args):
-        try:
-            data = self.manager.add_action_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                category_id=ctx["category_id"], value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"action_data": data}
-
-    def delete_action_data(self, ctx, args):
-        try:
-            data = self.manager.delete_action_data(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                   data_id=["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-
-class Assignments(object):
-
-    def __init__(self):
-        self.manager = PolicyManager
-
-    def __get_subject_id(self, ctx, subject_name):
-        data = self.manager.get_subjects(
-            user_id=ctx["user_id"],
-            policy_id=ctx["id"],
-            perimeter_id=None
-        )
-        for _data_id, _data_value in data.items():
-            if _data_value['name'] == subject_name:
-                return _data_id
-
-    def __get_object_id(self, ctx, object_name):
-        data = self.manager.get_objects(
-            user_id=ctx["user_id"],
-            policy_id=ctx["id"],
-            perimeter_id=None
-        )
-        for _data_id, _data_value in data.items():
-            if _data_value['name'] == object_name:
-                return _data_id
-
-    def __get_action_id(self, ctx, action_name):
-        data = self.manager.get_actions(
-            user_id=ctx["user_id"],
-            policy_id=ctx["id"],
-            perimeter_id=None
-        )
-        for _data_id, _data_value in data.items():
-            if _data_value['name'] == action_name:
-                return _data_id
-
-    def get_subject_assignments(self, ctx, args):
-        try:
-            if "perimeter_name" in ctx:
-                ctx["perimeter_id"] = self.__get_subject_id(ctx, ctx['perimeter_name'])
-            data = self.manager.get_subject_assignments(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                        subject_id=ctx["perimeter_id"], category_id=ctx["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subject_assignments": data}
-
-    def update_subject_assignment(self, ctx, args):
-        try:
-            data = self.manager.add_subject_assignment(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                       subject_id=args["id"], category_id=args["category_id"],
-                                                       data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"subject_assignments": data}
-
-    def delete_subject_assignment(self, ctx, args):
-        try:
-            data = self.manager.delete_subject_assignment(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                          subject_id=ctx["perimeter_id"], category_id=ctx["category_id"],
-                                                          data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_object_assignments(self, ctx, args):
-        try:
-            if "perimeter_name" in ctx:
-                ctx["perimeter_id"] = self.__get_object_id(ctx, ctx['perimeter_name'])
-            data = self.manager.get_object_assignments(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                       object_id=ctx["perimeter_id"], category_id=ctx["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"object_assignments": data}
-
-    def update_object_assignment(self, ctx, args):
-        try:
-            data = self.manager.add_object_assignment(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                      object_id=args["id"], category_id=args["category_id"],
-                                                      data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"object_assignments": data}
-
-    def delete_object_assignment(self, ctx, args):
-        try:
-            data = self.manager.delete_object_assignment(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                         object_id=ctx["perimeter_id"], category_id=ctx["category_id"],
-                                                         data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
-
-    def get_action_assignments(self, ctx, args):
-        try:
-            if "perimeter_name" in ctx:
-                ctx["perimeter_id"] = self.__get_action_id(ctx, ctx['perimeter_name'])
-            data = self.manager.get_action_assignments(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                       action_id=ctx["perimeter_id"], category_id=ctx["category_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"action_assignments": data}
-
-    def update_action_assignment(self, ctx, args):
-        try:
-            data = self.manager.add_action_assignment(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                      action_id=args["id"], category_id=args["category_id"],
-                                                      data_id=args["data_id"])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"action_assignments": data}
+    @check_auth
+    def delete(self, uuid=None, user_id=None):
+        """Delete a policy
 
-    def delete_action_assignment(self, ctx, args):
+        :param uuid: uuid of the policy to delete
+        :param user_id: user ID who do the request
+        :return: {
+            "result": "True or False",
+            "message": "optional message"
+        }
+        :internal_api: delete_policy
+        """
         try:
-            data = self.manager.delete_action_assignment(user_id=ctx["user_id"], policy_id=ctx["id"],
-                                                         action_id=ctx["perimeter_id"], category_id=ctx["category_id"],
-                                                         data_id=args["data_id"])
+            data = PolicyManager.delete_policy(user_id=user_id, policy_id=uuid)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
+                    "error": str(e)}
         return {"result": True}
 
+    @check_auth
+    def patch(self, uuid=None, user_id=None):
+        """Update a policy
 
-class Rules(object):
-
-    def __init__(self):
-        self.manager = PolicyManager
-
-    def get_rules(self, ctx, args):
+        :param uuid: uuid of the policy to update
+        :param user_id: user ID who do the request
+        :return: {
+            "policy_id1": {
+                "name": "...",
+                "model_id": "...",
+                "genre": "...",
+                "description": "...",
+            }
+        }
+        :internal_api: update_policy
+        """
         try:
-            data = self.manager.get_rules(user_id=ctx["user_id"],
-                                          policy_id=ctx["id"],
-                                          # meta_rule_id=ctx["meta_rule_id"],
-                                          rule_id=ctx["rule_id"])
+            data = PolicyManager.update_policy(user_id=user_id, policy_id=uuid, value=request.json)
         except Exception as e:
             LOG.error(e, exc_info=True)
             return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"rules": data}
-
-    def add_rule(self, ctx, args):
-        try:
-            data = self.manager.add_rule(user_id=ctx["user_id"],
-                                         policy_id=ctx["id"],
-                                         meta_rule_id=args["meta_rule_id"],
-                                         value=args)
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"rules": data}
+                    "error": str(e)}
+        return {"policies": data}
 
-    def delete_rule(self, ctx, args):
-        try:
-            data = self.manager.delete_rule(user_id=ctx["user_id"], policy_id=ctx["id"], rule_id=ctx['rule_id'])
-        except Exception as e:
-            LOG.error(e, exc_info=True)
-            return {"result": False,
-                    "error": str(e),
-                    "ctx": ctx, "args": args}
-        return {"result": True}
diff --git a/moonv4/moon_manager/moon_manager/api/rules.py b/moonv4/moon_manager/moon_manager/api/rules.py
new file mode 100644 (file)
index 0000000..8b1cf63
--- /dev/null
@@ -0,0 +1,130 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Rules (TODO)
+"""
+
+from flask import request
+from flask_restful import Resource
+from oslo_log import log as logging
+from moon_utilities.security_functions import call
+from moon_utilities.security_functions import check_auth
+from moon_db.core import PolicyManager
+
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.manager.api." + __name__)
+
+
+class Rules(Resource):
+    """
+    Endpoint for rules requests
+    """
+
+    __urls__ = ("/policies/<string:uuid>/rules",
+                "/policies/<string:uuid>/rules/",
+                "/policies/<string:uuid>/rules/<string:rule_id>",
+                "/policies/<string:uuid>/rules/<string:rule_id>/",
+                )
+
+    @check_auth
+    def get(self, uuid=None, rule_id=None, user_id=None):
+        """Retrieve all rules or a specific one
+
+        :param uuid: policy ID
+        :param rule_id: rule ID
+        :param user_id: user ID who do the request
+        :return: {
+            "rules": [
+                "policy_id": "policy_id1",
+                "meta_rule_id": "meta_rule_id1",
+                "rule_id1": ["subject_data_id1", "object_data_id1", "action_data_id1"],
+                "rule_id2": ["subject_data_id2", "object_data_id2", "action_data_id2"],
+            ]
+        }
+        :internal_api: get_rules
+        """
+        try:
+            data = PolicyManager.get_rules(user_id=user_id,
+                                           policy_id=uuid,
+                                           rule_id=rule_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"rules": data}
+
+    @check_auth
+    def post(self, uuid=None, rule_id=None, user_id=None):
+        """Add a rule to a meta rule
+
+        :param uuid: policy ID
+        :param rule_id: rule ID
+        :param user_id: user ID who do the request
+        :request body: post = {
+            "meta_rule_id": "meta_rule_id1",
+            "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"],
+            "instructions": (
+                {"decision": "grant"},
+            )
+            "enabled": True
+        }
+        :return: {
+            "rules": [
+                "meta_rule_id": "meta_rule_id1",
+                "rule_id1": {
+                    "rule": ["subject_data_id1", "object_data_id1", "action_data_id1"],
+                    "instructions": (
+                        {"decision": "grant"},  # "grant" to immediately exit, 
+                                                # "continue" to wait for the result of next policy
+                                                # "deny" to deny the request
+                    )
+                }
+                "rule_id2": {
+                    "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"],
+                    "instructions": (
+                        {
+                            "update": {
+                                "operation": "add",  # operations may be "add" or "delete"
+                                "target": "rbac:role:admin"  # add the role admin to the current user
+                            }
+                        },
+                        {"chain": {"name": "rbac"}}  # chain with the policy named rbac
+                    )
+                }
+            ]
+        }
+        :internal_api: add_rule
+        """
+        args = request.json
+        try:
+            data = PolicyManager.add_rule(user_id=user_id,
+                                          policy_id=uuid,
+                                          meta_rule_id=args['meta_rule_id'],
+                                          value=args)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"rules": data}
+
+    @check_auth
+    def delete(self, uuid=None, rule_id=None, user_id=None):
+        """Delete one rule linked to a specific sub meta rule
+
+        :param uuid: policy ID
+        :param rule_id: rule ID
+        :param user_id: user ID who do the request
+        :return: { "result": true }
+        :internal_api: delete_rule
+        """
+        try:
+            data = PolicyManager.delete_rule(user_id=user_id, policy_id=uuid, rule_id=rule_id)
+        except Exception as e:
+            LOG.error(e, exc_info=True)
+            return {"result": False,
+                    "error": str(e)}
+        return {"result": True}
+
diff --git a/moonv4/moon_manager/moon_manager/http_server.py b/moonv4/moon_manager/moon_manager/http_server.py
new file mode 100644 (file)
index 0000000..bdd429e
--- /dev/null
@@ -0,0 +1,136 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+
+from flask import Flask, jsonify
+from flask_cors import CORS, cross_origin
+from flask_restful import Resource, Api
+import logging
+from moon_manager import __version__
+from moon_manager.api.generic import Status, Logs, API
+from moon_manager.api.models import Models
+from moon_manager.api.policies import Policies
+from moon_manager.api.pdp import PDP
+from moon_manager.api.meta_rules import MetaRules
+from moon_manager.api.meta_data import SubjectCategories, ObjectCategories, ActionCategories
+from moon_manager.api.perimeter import Subjects, Objects, Actions
+from moon_manager.api.data import SubjectData, ObjectData, ActionData
+from moon_manager.api.assignments import SubjectAssignments, ObjectAssignments, ActionAssignments
+from moon_manager.api.rules import Rules
+from moon_utilities import configuration, exceptions
+
+logger = logging.getLogger("moon.manager.http")
+
+
+class Server:
+    """Base class for HTTP server"""
+
+    def __init__(self, host="localhost", port=80, api=None, **kwargs):
+        """Run a server
+
+        :param host: hostname of the server
+        :param port: port for the running server
+        :param kwargs: optional parameters
+        :return: a running server
+        """
+        self._host = host
+        self._port = port
+        self._api = api
+        self._extra = kwargs
+
+    @property
+    def host(self):
+        return self._host
+
+    @host.setter
+    def host(self, name):
+        self._host = name
+
+    @host.deleter
+    def host(self):
+        self._host = ""
+
+    @property
+    def port(self):
+        return self._port
+
+    @port.setter
+    def port(self, number):
+        self._port = number
+
+    @port.deleter
+    def port(self):
+        self._port = 80
+
+    def run(self):
+        raise NotImplementedError()
+
+__API__ = (
+    Status, Logs, API,
+    MetaRules, SubjectCategories, ObjectCategories, ActionCategories,
+    Subjects, Objects, Actions,
+    SubjectAssignments, ObjectAssignments, ActionAssignments,
+    SubjectData, ObjectData, ActionData,
+    Rules,
+    Models, Policies, PDP
+ )
+
+
+class Root(Resource):
+    """
+    The root of the web service
+    """
+    __urls__ = ("/", )
+    __methods = ("get", "post", "put", "delete", "options")
+
+    def get(self):
+        tree = {"/": {"methods": ("get",), "description": "List all methods for that service."}}
+        for item in __API__:
+            tree[item.__name__] = {"urls": item.__urls__}
+            _methods = []
+            for _method in self.__methods:
+                if _method in dir(item):
+                    _methods.append(_method)
+            tree[item.__name__]["methods"] = _methods
+            tree[item.__name__]["description"] = item.__doc__.strip()
+        return {
+            "version": __version__,
+            "tree": tree
+        }
+
+
+class HTTPServer(Server):
+
+    def __init__(self, host="localhost", port=80, **kwargs):
+        super(HTTPServer, self).__init__(host=host, port=port, **kwargs)
+        self.app = Flask(__name__)
+        conf = configuration.get_configuration("components/manager")
+        self.manager_hostname = conf["components/manager"].get("hostname", "manager")
+        self.manager_port = conf["components/manager"].get("port", 80)
+        #Todo : specify only few urls instead of *
+        CORS(self.app)
+        self.api = Api(self.app)
+        self.__set_route()
+        self.__hook_errors()
+
+    def __hook_errors(self):
+
+        def get_404_json(e):
+            return jsonify({"result": False, "code": 404, "description": str(e)}), 404
+        self.app.register_error_handler(404, get_404_json)
+
+        def get_400_json(e):
+            return jsonify({"result": False, "code": 400, "description": str(e)}), 400
+        self.app.register_error_handler(400, lambda e: get_400_json)
+        self.app.register_error_handler(403, exceptions.AuthException)
+
+    def __set_route(self):
+        self.api.add_resource(Root, '/')
+
+        for api in __API__:
+            self.api.add_resource(api, *api.__urls__)
+
+    def run(self):
+        self.app.run(debug=True, host=self._host, port=self._port)  # nosec
+
diff --git a/moonv4/moon_manager/moon_manager/messenger.py b/moonv4/moon_manager/moon_manager/messenger.py
deleted file mode 100644 (file)
index 76ba6da..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
-# This software is distributed under the terms and conditions of the 'Apache-2.0'
-# license which can be found in the file 'LICENSE' in this package distribution
-# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
-
-import time
-from oslo_config import cfg
-import oslo_messaging
-from oslo_log import log as logging
-from moon_manager.api.generic import Status, Logs
-from moon_utilities.api import APIList
-from moon_manager.api.models import Models, MetaRules, MetaData
-from moon_manager.api.policies import Policies, Perimeter, Data, Assignments, Rules
-from moon_manager.api.pdp import PDP
-from moon_manager.api.master import Master
-from moon_utilities.security_functions import call
-from moon_utilities.exceptions import IntraExtensionUnknown
-from moon_utilities import configuration
-
-LOG = logging.getLogger("moon.manager.messenger")
-CONF = cfg.CONF
-
-
-class Server:
-
-    def __init__(self):
-        self.TOPIC = "moon_manager"
-        cfg.CONF.transport_url = self.__get_transport_url()
-        self.transport = oslo_messaging.get_transport(cfg.CONF)
-        self.target = oslo_messaging.Target(topic=self.TOPIC, server='moon_manager_server1')
-        # ctx = {'user_id': 'admin', 'id': intra_extension_id, 'method': 'get_intra_extensions'}
-        # if CONF.slave.slave_name:
-        #     ctx['call_master'] = True
-        # intra_extension = call(
-        #     endpoint="security_router",
-        #     ctx=ctx,
-        #     method='route',
-        #     args={}
-        # )
-        LOG.info("Starting MQ server with topic: {}".format(self.TOPIC))
-        # if "intra_extensions" not in intra_extension:
-        #     LOG.error("Error reading intra_extension from router")
-        #     LOG.error("intra_extension: {}".format(intra_extension))
-        #     raise IntraExtensionUnknown
-        # intra_extension_id = list(intra_extension["intra_extensions"].keys())[0]
-        self.endpoints = [
-            APIList((Status, Logs)),
-            Status(),
-            Logs(),
-            Models(),
-            MetaRules(),
-            MetaData(),
-            Policies(),
-            Perimeter(),
-            Data(),
-            Assignments(),
-            Rules(),
-            PDP(),
-            Master()
-        ]
-        self.server = oslo_messaging.get_rpc_server(self.transport, self.target, self.endpoints,
-                                                    executor='threading',
-                                                    access_policy=oslo_messaging.DefaultRPCAccessPolicy)
-
-    @staticmethod
-    def __get_transport_url():
-        messenger = configuration.get_configuration(configuration.MESSENGER)["messenger"]
-        return messenger['url']
-
-    def run(self):
-        try:
-            self.server.start()
-            while True:
-                time.sleep(1)
-        except KeyboardInterrupt:
-            print("Stopping server by crtl+c")
-        except SystemExit:
-            print("Stopping server")
-
-        self.server.stop()
-        self.server.wait()
-
index 56ba1e9..c317e31 100644 (file)
@@ -6,8 +6,8 @@
 import os
 from oslo_config import cfg
 from oslo_log import log as logging
-from moon_utilities import configuration
-from moon_manager.messenger import Server
+from moon_utilities import configuration, exceptions
+from moon_manager.http_server import HTTPServer
 
 LOG = logging.getLogger("moon.manager")
 CONF = cfg.CONF
@@ -18,8 +18,18 @@ __CWD__ = os.path.dirname(os.path.abspath(__file__))
 
 def main():
     configuration.init_logging()
-    configuration.add_component("manager", "manager")
-    server = Server()
+    try:
+        conf = configuration.get_configuration("components/manager")
+        hostname = conf["components/manager"].get("hostname", "manager")
+        port = conf["components/manager"].get("port", 80)
+        bind = conf["components/manager"].get("bind", "127.0.0.1")
+    except exceptions.ConsulComponentNotFound:
+        hostname = "manager"
+        bind = "127.0.0.1"
+        port = 80
+        configuration.add_component(uuid="manager", name=hostname, port=port, bind=bind)
+    LOG.info("Starting server with IP {} on port {} bind to {}".format(hostname, port, bind))
+    server = HTTPServer(host=bind, port=port)
     server.run()
 
 
index 7609c3d..e7be3d0 100644 (file)
@@ -1,8 +1,5 @@
-kombu !=4.0.1,!=4.0.0
-oslo.messaging
-oslo.config
-vine
-oslo.log
-babel
+flask
+flask_restful
+flask_cors
 moon_utilities
 moon_db
\ No newline at end of file