Example #1
0
File: rules.py Project: bcgov/OCWA
def write_rules() -> object:
    """
    (Over)write a set of rules
    :return: JSON of success message or error message
    """

    db=Db()

    body = request.get_json()

    if not('rule_set' in body):
        return jsonify({"error": "rule_set is a required attribute"})

    rule_set = body['rule_set']

    rules = None
    try:
        rules = hcl.loads(rule_set)
    except Exception as e:
        return jsonify({"error": "%s%s" % (str(e),rule_set)})

    for ruleName, ruleDef in rules['rule'].items():
        dbRule = db.Rules(
            name=ruleName,
            source=ruleDef['source']
        )

        if 'mandatory' in ruleDef:
            db.Rules.objects(name=ruleName).update_one(source=ruleDef['source'], mandatory=ruleDef['mandatory'], upsert=True, write_concern=None)
        else:
            db.Rules.objects(name=ruleName).update_one(source=ruleDef['source'], upsert=True, write_concern=None)

    return jsonify({"success": "Written successfully"})
Example #2
0
def validate_policy(fileId: str) -> object:
    """
    Validates a file
    :param fileId: File Object ID
    :return: JSON of submission state
    """

    policy = getPolicies()

    db = Db()

    for key, val in policy.items():
        results = db.Results.objects(file_id=fileId, rule_id=key)

        if (len(results) == 0):
            result = db.Results(file_id=fileId,
                                message="",
                                rule_id=key,
                                state=2)

            result.save()
            v = Validator(policy[key], result)
            v.startValidate()

    return jsonify({"message": "Successful"}), http.HTTPStatus.CREATED
Example #3
0
def validate_rule(fileId: str, ruleId: str) -> object:
    """
    Validates a file with specific rule
    :param fileId: File Object ID
    :param ruleId: Rule Object ID
    :return: JSON of submission state
    """

    db = Db()
    results = db.Results.objects(file_id=fileId, rule_id=ruleId)
    if len(results) == 0:
        return jsonify({
            "error": "Can't rerun a rule that hasn't been bulk run"
        }), HTTPStatus.BAD_REQUEST

    if len(results) == 1:
        result = results[0]
        result.state = 2
        result.save()

        rule = get_rule(ruleId)

        if len(rule) == 1 and rule[0]['name'] == ruleId:
            v = Validator()
            v.start_validate(rule[0], result)

            return jsonify({"message": "Successful"}), HTTPStatus.OK
        else:
            return jsonify({"error": "Rule not found"
                            }), HTTPStatus.INTERNAL_SERVER_ERROR
Example #4
0
def validate_rule(fileId: str, ruleId: str) -> object:
    """
    Validates a file with specific rule
    :param fileId: File Object ID
    :param ruleId: Rule Object ID
    :return: JSON of submission state
    """

    db = Db()
    results = db.Results.objects(file_id=fileId, rule_id=ruleId)
    if len(results) == 0:
        return jsonify({
            "error": "Can't rerun a rule that hasn't been bulk run"
        }), http.HTTPStatus.BAD_REQUEST

    if len(results) == 1:
        result = results[0]
        result.state = 2
        result.save()

        policy = getPolicy(None)

        if result.rule_id in policy.keys():
            v = Validator(policy[result.rule_id], result)
            v.startValidate()

            return jsonify({"message": "Successful"}), http.HTTPStatus.OK
        else:
            return jsonify({"error": "Rule not found in policy"
                            }), http.HTTPStatus.INTERNAL_SERVER_ERROR

    return jsonify({"error": "Couldn't decide on the rule to replace"
                    }), http.HTTPStatus.INTERNAL_SERVER_ERROR
Example #5
0
def write_rule(ruleName: str) -> object:
    """
    (Over)write a single rule
    :param ruleName: Rule Name
    :return: JSON of success message or error message
    """

    db=Db()

    body = request.get_json()

    if not('rule' in body):
        return jsonify({"error": "rule is a required attribute"})

    pol = body['rule']

    rule = None

    try:
        rule = hcl.loads(pol)
    except Exception as e:
        return jsonify({"error": str(e)})

    if not('rule' in rule):
        return jsonify({"error": "Invalid json"})

    if not (ruleName in rule['rule']):
        return jsonify({"error": "rule name mismatch with provided hcl and url"})

    if not ('source' in rule['rule'][ruleName]):
        return jsonify({"error": "source is a required attribute"})

    dbRule = db.Rules(
        name=ruleName,
        source=rule['rule'][ruleName]['source']
    )

    if 'mandatory' in rule['rule'][ruleName]:
        db.Rules.objects(name=ruleName).update_one(source=rule['rule'][ruleName]['source'], mandatory=rule['rule'][ruleName]['mandatory'], upsert=True, write_concern=None)
    else:
        db.Rules.objects(name=ruleName).update_one(source=rule['rule'][ruleName]['source'], upsert=True, write_concern=None)




    return jsonify({"success": "Written successfully"})
Example #6
0
def get_file_results(fileId: str) -> object:
    """
    Returns the result of file
    :param fileId: File Object ID
    :return: JSON of validation result
    """

    db = Db()
    return db.Results.objects(file_id=fileId).to_json()
Example #7
0
def get_rule_result(fileId: str, ruleId: str) -> object:
    """
    Returns the result of file with specific rule
    :param fileId: File Object ID
    :param ruleId: Rule Object ID
    :return: JSON of validation result
    """
    db = Db()
    return db.Results.objects(file_id=fileId, rule_id=ruleId).to_json()
Example #8
0
def validate_policy(policyName: str, fileId: str) -> object:
    """
    Validates a file
    :param fileId: File Object ID
    :return: JSON of submission state
    """

    policy = get_policy(policyName)

    db = Db()

    log.debug("Policies")
    log.debug(policy)
    for i in range(len(policy)):
        log.debug("rule")
        log.debug(policy[i])
        results = db.Results.objects(file_id=fileId, rule_id=policy[i]['name'])

        log.debug("checking result length")
        log.debug(fileId)
        log.debug(policy[i]['name'])
        log.debug(results)

        conf = Config().data

        alwaysScan = conf.get('alwaysScanFiles', False)

        if ((len(results) == 0) or (alwaysScan)):
            log.debug("no results")
            result = db.Results(file_id=fileId,
                                message="",
                                rule_id=policy[i]['name'],
                                state=2,
                                mandatory=policy[i]['mandatory'])

            if alwaysScan and len(results) > 0:
                result = results[0]

            result.save()
            v = Validator()
            v.start_validate(policy[i], result)

    return jsonify({"message": "Successful"}), HTTPStatus.CREATED
Example #9
0
File: rules.py Project: bcgov/OCWA
def get_rule(ruleName: str) -> object:
    """
    Gets a rule
    :param ruleName: Rule Name
    :return: JSON of submission state
    """

    db=Db()

    return db.Rules.objects(name=ruleName).to_json()
Example #10
0
def get_policy() -> object:
    """
    Get policy
    :return: JSON of policy (collection of rules)
    """

    db = Db()
    resp = Response()
    resp.headers['Content-Type'] = ["application/json"]
    return db.Rules.objects().to_json()
Example #11
0
def write_policy() -> object:
    """
    (Over)write policy
    :return: JSON of success message or error message
    """

    db=Db()

    body = request.get_json()

    if not('policy' in body):
        return jsonify({"error": "policy is a required attribute"})
    pol = body['policy']

    policy = None

    try:
        policy = hcl.loads(pol)
    except Exception as e:
        return jsonify({"error": str(e)})

    if not('rule' in policy):
        return jsonify({"error": "Invalid json"})


    ##Clear all entries!!!
    db.Rules.objects().delete()

    for ruleName, ruleDef in policy['rule'].items():
        rule = db.Rules(
            name=ruleName,
            source=ruleDef['source']
        )

        if 'mandatory' in ruleDef:
            rule.mangatory = ruleDef['mandatory']

        rule.save()


    return jsonify({"success": "Written successfully"})
Example #12
0
File: rules.py Project: bcgov/OCWA
def write_policy() -> object:
    """
    (Over)write policy
    :return: JSON of success message or error message
    """

    db=Db()

    body = request.get_json()

    if not('name' in body):
        return jsonify({"error": "name is a required attribute"})

    if not('rules' in body):
        return jsonify({"error": "'rules' is a required attribute"})
    name = body['name']
    rules = body['rules']

    if len(rules) == 0:
        return jsonify({"error": "policy must have atleast one rule"})

    db.Policies(name=name, rules=rules).save()

    return jsonify({"success": "Written successfully"})
Example #13
0
File: rules.py Project: bcgov/OCWA
def get_policy(policyName: str) -> object:
    """
    Get policy
    :return: JSON of policy (collection of rules)
    """
    db = Db()
    resp = Response()
    resp.headers['Content-Type'] = ["application/json"]

    policy = db.Policies.objects(name=policyName).first()

    rules = db.Rules.objects(name__in=policy.rules)

    if len(policy.rules) != len(rules):
        raise Exception("Missing rules from policy")

    return rules.to_json()
Example #14
0
def get_files_results() -> object:
    """
    Returns the results of files
    :return: JSON array of validation results
    """

    if 'files' in request.args:
        files = request.args.get('files').split(',')
        if len(files) > 25:
            return jsonify({
                "error":
                "Too many files specified.  Max 25 allowed."
            }), HTTPStatus.INTERNAL_SERVER_ERROR
    else:
        return jsonify({"error": "Atleast one file ID must be specified."
                        }), HTTPStatus.INTERNAL_SERVER_ERROR

    db = Db()
    return db.Results.objects(file_id__in=files).to_json()
Example #15
0
File: rules.py Project: bcgov/OCWA
def update_policy(policyName: str) -> object:
    """
    (Over)write policy
    :return: JSON of success message or error message
    """

    db=Db()

    body = request.get_json()

    if not('rules' in body):
        return jsonify({"error": "'rules' is a required attribute"})

    rules = body['rules']

    if len(rules) == 0:
        return jsonify({"error": "policy must have atleast one rule"})

    p = db.Policies.objects(name=policyName).first()
    p.rules = rules
    p.save()

    return jsonify({"success": "Written successfully"})