Esempio n. 1
0
def add_rule(policy_id, meta_rule_id, value=None):
    from python_moondb.core import PolicyManager
    if not value:
        meta_rule = meta_rule_helper.get_meta_rules(meta_rule_id)
        sub_cat_id = meta_rule[meta_rule_id]['subject_categories'][0]
        ob_cat_id = meta_rule[meta_rule_id]['object_categories'][0]
        act_cat_id = meta_rule[meta_rule_id]['action_categories'][0]

        subject_data_id = mock_data.create_subject_data(policy_id=policy_id,
                                                        category_id=sub_cat_id)
        object_data_id = mock_data.create_object_data(policy_id=policy_id,
                                                      category_id=ob_cat_id)
        action_data_id = mock_data.create_action_data(policy_id=policy_id,
                                                      category_id=act_cat_id)

        value = {
            "rule": (subject_data_id, object_data_id, action_data_id),
            "instructions": ({
                "decision": "grant"
            }),
            "enabled": "",
        }
    return PolicyManager.add_rule("", policy_id, meta_rule_id, value)
Esempio n. 2
0
    def delete(self, uuid=None, perimeter_id=None, user_id=None):
        """Delete a subject for a given policy

        :param uuid: uuid of the policy (mandatory if perimeter_id is not set)
        :param perimeter_id: uuid of the subject (mandatory if uuid is not set)
        :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 (optional)",
                    "password": "******",
                    "email": "email address of the subject (optional)"
            }
        }
        :internal_api: delete_subject
        """

        data = PolicyManager.delete_subject(user_id=user_id,
                                            policy_id=uuid,
                                            perimeter_id=perimeter_id)

        return {"result": True}
Esempio n. 3
0
    def patch(self, uuid=None, user_id=None):
        """Update a policy

        :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 = PolicyManager.update_policy(user_id=user_id,
                                               policy_id=uuid,
                                               value=request.json)
        except Exception as e:
            logger.error(e, exc_info=True)
            return {"result": False, "error": str(e)}, 500
        return {"policies": data}
Esempio n. 4
0
    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 (optional)"
        }
        :return: {
                "action_id": {
                    "name": "name of the action",
                    "description": "description of the action (optional)"
            }
        }
        :internal_api: set_action
        """
        data = PolicyManager.update_action(user_id=user_id,
                                           perimeter_id=perimeter_id,
                                           value=request.json)

        return {"actions": data}
Esempio n. 5
0
    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:
            logger.error(e, exc_info=True)
            return {"result": False, "error": str(e)}, 500
        return {"actions": data}
Esempio n. 6
0
    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:
            logger.error(e, exc_info=True)
            return {"result": False,
                    "error": str(e)}, 500
        return {"subject_assignments": data}
Esempio n. 7
0
    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 (mandatory)",
            "object_description": "description of the object (optional)"
        }
        :return: {
                "object_id": {
                    "name": "name of the object",
                    "description": "description of the object (optional)"
            }
        }
        :internal_api: set_object
        """
        data = PolicyManager.add_object(user_id=user_id,
                                        policy_id=uuid,
                                        perimeter_id=perimeter_id,
                                        value=request.json)

        return {"objects": data}
Esempio n. 8
0
def get_policies():
    from python_moondb.core import PolicyManager
    return PolicyManager.get_policies("admin")
Esempio n. 9
0
def delete_subject_data(policy_id, data_id):
    from python_moondb.core import PolicyManager
    PolicyManager.delete_subject_data("", policy_id, data_id)
Esempio n. 10
0
def get_subjects(policy_id, perimeter_id=None):
    from python_moondb.core import PolicyManager
    return PolicyManager.get_subjects("", policy_id, perimeter_id)
Esempio n. 11
0
def delete_rule(policy_id=None, rule_id=None):
    from python_moondb.core import PolicyManager
    PolicyManager.delete_rule("", policy_id, rule_id)
Esempio n. 12
0
def delete_subject_assignment(policy_id, subject_id, category_id, data_id):
    from python_moondb.core import PolicyManager
    PolicyManager.delete_subject_assignment("", policy_id, subject_id,
                                            category_id, data_id)
Esempio n. 13
0
def add_action_data(policy_id, data_id=None, category_id=None, value=None):
    from python_moondb.core import PolicyManager
    return PolicyManager.add_action_data("", policy_id, data_id, category_id, value)
Esempio n. 14
0
def delete_action_data(policy_id, data_id):
    from python_moondb.core import PolicyManager
    PolicyManager.delete_action_data("", policy_id=policy_id, data_id=data_id)
Esempio n. 15
0
def update_policy(policy_id, value):
    from python_moondb.core import PolicyManager
    return PolicyManager.update_policy("admin", policy_id, value)
Esempio n. 16
0
    def _import_rules(self, json_rules):
        if not isinstance(json_rules, list):
            raise InvalidJson("rules shall be a list!")

        for json_rule in json_rules:
            json_to_use = dict()
            JsonUtils.copy_field_if_exists(json_rule, json_to_use,
                                           "instructions", str)
            JsonUtils.copy_field_if_exists(json_rule,
                                           json_to_use,
                                           "enabled",
                                           bool,
                                           default_value=True)

            json_ids = dict()
            JsonUtils.convert_name_to_id(json_rule, json_ids, "policy",
                                         "policy_id", "policy", PolicyManager,
                                         self._user_id)
            JsonUtils.convert_name_to_id(json_rule, json_to_use, "meta_rule",
                                         "meta_rule_id", "meta_rule",
                                         ModelManager, self._user_id)
            json_subject_ids = dict()
            json_object_ids = dict()
            json_action_ids = dict()
            JsonUtils.convert_names_to_ids(json_rule["rule"], json_subject_ids,
                                           "subject_data", "subject",
                                           "subject_data", PolicyManager,
                                           self._user_id,
                                           json_ids["policy_id"])
            JsonUtils.convert_names_to_ids(json_rule["rule"], json_object_ids,
                                           "object_data", "object",
                                           "object_data", PolicyManager,
                                           self._user_id,
                                           json_ids["policy_id"])
            JsonUtils.convert_names_to_ids(json_rule["rule"], json_action_ids,
                                           "action_data", "action",
                                           "action_data", PolicyManager,
                                           self._user_id,
                                           json_ids["policy_id"])

            meta_rule = ModelManager.get_meta_rules(
                self._user_id, json_to_use["meta_rule_id"])
            meta_rule = [v for v in meta_rule.values()]
            meta_rule = meta_rule[0]

            json_to_use_rule = self._reorder_rules_ids(
                json_rule, meta_rule["subject_categories"],
                json_subject_ids["subject"], json_ids["policy_id"],
                PolicyManager.get_subject_data)
            json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(
                json_rule, meta_rule["object_categories"],
                json_object_ids["object"], json_ids["policy_id"],
                PolicyManager.get_object_data)
            json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(
                json_rule, meta_rule["action_categories"],
                json_action_ids["action"], json_ids["policy_id"],
                PolicyManager.get_action_data)
            json_to_use["rule"] = json_to_use_rule
            try:
                logger.debug("Adding / updating a rule from json {}".format(
                    json_to_use))
                PolicyManager.add_rule(self._user_id, json_ids["policy_id"],
                                       json_to_use["meta_rule_id"],
                                       json_to_use)
            except exceptions.RuleExisting:
                pass
            except exceptions.PolicyUnknown:
                raise UnknownPolicy("Unknown policy with id {}".format(
                    json_ids["policy_id"]))
Esempio n. 17
0
def add_subject(policy_id, perimeter_id=None, value=None):
    from python_moondb.core import PolicyManager
    return PolicyManager.add_subject("", policy_id, perimeter_id, value)
Esempio n. 18
0
    def _import_policies(self, json_policies):
        policy_mandatory_ids = []

        if not isinstance(json_policies, list):
            raise InvalidJson("policies shall be a list!")

        for json_policy in json_policies:
            # TODO put this in moondb
            # policy_in_db = PolicyManager.get_policies_by_name(json_without_model_name["name"])
            policies = PolicyManager.get_policies(self._user_id)
            policy_in_db = None
            policy_id = None
            for policy_key in policies:
                if policies[policy_key]["name"] == json_policy["name"]:
                    policy_in_db = policies[policy_key]
                    policy_id = policy_key
            # end TODO
            if policy_in_db is None:
                policy_does_exist = False
            else:
                policy_does_exist = True

            policy_override = JsonUtils.get_override(json_policy)
            policy_mandatory = JsonUtils.get_mandatory(json_policy)

            if policy_override is False and policy_does_exist:
                if policy_id:
                    policy_mandatory_ids.append(policy_id)
                    logger.warning(
                        "Existing policy not updated because of the override option is not set !"
                    )
                    continue

            json_without_model_name = dict()
            JsonUtils.copy_field_if_exists(json_policy,
                                           json_without_model_name, "name",
                                           str)
            JsonUtils.copy_field_if_exists(json_policy,
                                           json_without_model_name,
                                           "description", str)
            JsonUtils.copy_field_if_exists(json_policy,
                                           json_without_model_name, "genre",
                                           str)
            JsonUtils.convert_name_to_id(json_policy,
                                         json_without_model_name,
                                         "model",
                                         "model_id",
                                         "model",
                                         ModelManager,
                                         self._user_id,
                                         field_mandatory=False)

            if not policy_does_exist:
                logger.debug(
                    "Creating policy {} ".format(json_without_model_name))
                added_policy = PolicyManager.add_policy(
                    self._user_id, None, json_without_model_name)
                if policy_mandatory is True:
                    keys = list(added_policy.keys())
                    policy_mandatory_ids.append(keys[0])
            elif policy_override is True:
                logger.debug(
                    "Updating policy {} ".format(json_without_model_name))
                updated_policy = PolicyManager.update_policy(
                    self._user_id, policy_id, json_without_model_name)
                if policy_mandatory is True:
                    policy_mandatory_ids.append(policy_id)
        return policy_mandatory_ids
Esempio n. 19
0
    def _import_subject_object_action_assignments(self, json_item_assignments,
                                                  type_element):
        import_method = getattr(PolicyManager,
                                'add_' + type_element + '_assignment')
        get_method = getattr(PolicyManager, 'get_' + type_element + '_data')

        if not isinstance(json_item_assignments, list):
            raise InvalidJson(type_element + " assignments shall be a list!")

        # get the policy id related to the user
        policies = PolicyManager.get_policies(self._user_id)

        for json_item_assignment in json_item_assignments:
            item_override = JsonUtils.get_override(json_item_assignment)
            if item_override is True:
                raise ForbiddenOverride(
                    "{} assignments do not support override flag !".format(
                        type_element))

            json_assignment = dict()
            JsonUtils.convert_name_to_id(json_item_assignment, json_assignment,
                                         "category", "category_id",
                                         type_element + "_category",
                                         ModelManager, self._user_id)

            has_found_data = False
            # loop over policies
            for policy_id in policies:
                json_data = dict()
                try:
                    JsonUtils.convert_name_to_id(json_item_assignment,
                                                 json_assignment, type_element,
                                                 "id", type_element,
                                                 PolicyManager, self._user_id,
                                                 policy_id)
                    JsonUtils.convert_names_to_ids(
                        json_item_assignment, json_data, "assignments",
                        "data_id", type_element + "_data", PolicyManager,
                        self._user_id, policy_id,
                        json_assignment["category_id"])
                    has_found_data = True
                except UnknownName:
                    # the category or data has not been found in this policy : we look into the next one
                    continue
                for data_id in json_data["data_id"]:
                    # find the policy related to the current data
                    data = get_method(self._user_id, policy_id, data_id,
                                      json_assignment["category_id"])
                    if data is not None and len(data) == 1:
                        logger.debug(
                            "Adding / updating a {} assignment from json {}".
                            format(type_element, json_assignment))
                        import_method(self._user_id, policy_id,
                                      json_assignment["id"],
                                      json_assignment["category_id"], data_id)
                    else:
                        raise UnknownData(
                            "Unknown data with id {}".format(data_id))

            # case the data has not been found in any policies
            if has_found_data is False:
                raise InvalidJson(
                    "The json contains unknown {} data or category : {}".
                    format(type_element, json_item_assignment))
Esempio n. 20
0
def get_available_metadata(policy_id):
    from python_moondb.core import PolicyManager
    return PolicyManager.get_available_metadata("", policy_id)
Esempio n. 21
0
def get_action_data(policy_id, data_id=None, category_id=None):
    from python_moondb.core import PolicyManager
    return PolicyManager.get_action_data("", policy_id, data_id, category_id)
Esempio n. 22
0
def get_policy_from_meta_rules(meta_rule_id):
    from python_moondb.core import PolicyManager
    return PolicyManager.get_policy_from_meta_rules("admin", meta_rule_id)
Esempio n. 23
0
def get_subject_assignments(policy_id, subject_id=None, category_id=None):
    from python_moondb.core import PolicyManager
    return PolicyManager.get_subject_assignments("", policy_id, subject_id,
                                                 category_id)
Esempio n. 24
0
def get_rules(policy_id=None, meta_rule_id=None, rule_id=None):
    from python_moondb.core import PolicyManager
    return PolicyManager.get_rules("", policy_id, meta_rule_id, rule_id)
Esempio n. 25
0
def add_action_assignment(policy_id, action_id, category_id, data_id):
    from python_moondb.core import PolicyManager
    return PolicyManager.add_action_assignment("", policy_id, action_id,
                                               category_id, data_id)
Esempio n. 26
0
def delete_subject(policy_id, perimeter_id):
    from python_moondb.core import PolicyManager
    PolicyManager.delete_subject("", policy_id, perimeter_id)