示例#1
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"]))
示例#2
0
    def _import_subject_object_action_datas(self, json_items_data,
                                            mandatory_policy_ids,
                                            type_element):
        if type_element == "subject":
            import_method = getattr(PolicyManager,
                                    'set_' + type_element + '_data')
        else:
            import_method = getattr(PolicyManager,
                                    'add_' + type_element + '_data')
        # get_method = getattr(PolicyManager, 'get_' + type_element + '_data')

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

        for json_item_data in json_items_data:
            item_override = JsonUtils.get_override(json_items_data)
            if item_override is True:
                raise ForbiddenOverride(
                    "{} datas do not support override flag !".format(
                        type_element))
            json_to_use = dict()
            JsonUtils.copy_field_if_exists(json_item_data, json_to_use, "name",
                                           str)
            JsonUtils.copy_field_if_exists(json_item_data, json_to_use,
                                           "description", str)
            json_policy = dict()
            # field_mandatory : not mandatory if there is some mandatory policies
            JsonUtils.convert_names_to_ids(
                json_item_data,
                json_policy,
                "policies",
                "policy_id",
                "policy",
                PolicyManager,
                self._user_id,
                field_mandatory=len(mandatory_policy_ids) == 0)
            json_category = dict()
            JsonUtils.convert_name_to_id(json_item_data, json_category,
                                         "category", "category_id",
                                         type_element + "_category",
                                         ModelManager, self._user_id)
            policy_ids = []
            if "policy_id" in json_policy:
                policy_ids = json_policy["policy_id"]

            for policy_id in policy_ids:
                if policy_id is not None and policy_id not in mandatory_policy_ids:
                    mandatory_policy_ids.append(policy_id)

            if len(mandatory_policy_ids) == 0:
                raise InvalidJson(
                    "Invalid data, the policy shall be set when importing {}".
                    format(json_item_data))
            category_id = None
            if "category_id" in json_category:
                category_id = json_category["category_id"]
            if category_id is None:
                raise InvalidJson(
                    "Invalid data, the category shall be set when importing {}"
                    .format(json_item_data))

            for policy_id in mandatory_policy_ids:
                try:
                    data = import_method(self._user_id,
                                         policy_id,
                                         category_id=category_id,
                                         value=json_to_use)
                except exceptions.PolicyUnknown:
                    raise UnknownPolicy(
                        "Unknown policy with id {}".format(policy_id))
                except Exception as e:
                    logger.exception(str(e))
                    raise e
示例#3
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
示例#4
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))