使用Rego针对另一个列表验证列表的每个元素

问题描述

我是新来的,我想写一个策略来针对另一个列表验证列表中的元素。这是我要解决的问题: 我有一个批准的安全组列表,需要从输入中检查这些安全组。如果输入的SG不在批准列表中,则我需要输出一条消息,指出“正在使用无效的SG”。 我找不到任何说明如何将一个列表与另一个列表进行比较的文档。 这是雷哥游乐场的政策:https://play.openpolicyagent.org/p/m09f2K1g0h

政策:

check_list = ["sg-1001a1d199tx8866a","sg-2002b2e200in9966b","sg-3003c3f201dc0011c","sg-4004d4e202nj1122d","sg-5003c3f201dc0011e","sg-6004d4e202nj1122f"]

aws_valid_sgs := {i: Reason |
    doc = input[i]; i="aws_launch_configuration.ecs-cluster-lc"
    key_ids := [k | doc[k]; startswith(k,"security_groups.")]
    resource := {
        doc[k] : doc[replace(k,".key",".value")] | key_ids[_] == k
    }
    
    sg_ids := [m | resource[m]; startswith(m,"sg-")]
    list := {x| x:=check_list[_]}

    not(list[sg_ids[i]])

    Reason := sprintf("Resource %v is not using an approved SG ",[doc.name])
}

输入:

{
    "aws_launch_configuration.ecs-cluster-lc": {
        "associate_public_ip_address": "false","destroy": false,"destroy_tainted": false,"ebs_block_device.#": "","ebs_optimized": "","enable_monitoring": "true","id": "","instance_type": "t3.large","key_name": "","name": "test_r1-us-east-1","security_groups.1122334455": "sg-1001a1d199tx8866a","security_groups.2233445566": "sg-2002b2e200in9966b","security_groups.3344556677": "sg-3003c3f201dc0011c","security_groups.4455667788": "sg-4004d4e202nj1122d"
    },"destroy": false
}

感谢您的帮助。谢谢。

解决方法

TLDR;最好使用 set 操作(例如{"foo","bar","baz"} - {"bar"} == {"foo","baz"})来完成。这是一个完整的示例:


# Define a SET of valid SGs to compare against.
valid_sgs := {"sg-1001a1d199tx8866a","sg-2002b2e200in9966b","sg-3003c3f201dc0011c","sg-4004d4e202nj1122d","sg-5003c3f201dc0011e","sg-6004d4e202nj1122f"}

# Compute the SET of SGs from the launch configuration in the input.
launch_config_sgs := {sg |
    some key
    launch_config := input["aws_launch_configuration.ecs-cluster-lc"]
    sg := launch_config[key]
    startswith(key,"security_groups.")
}

# Compute the SET of invalid SGs by taking the difference of the other two sets.
invalid_launch_config_sgs := launch_config_sgs - valid_sgs

# Generate a 'deny' message if there are any invalid SGs.
deny[msg] {
    launch_config := input["aws_launch_configuration.ecs-cluster-lc"]
    count(invalid_launch_config_sgs) > 0
    msg := sprintf("Resource %v is not using an approved SG",[launch_config.name])
}

Playground link

海报的某些版本使问题变得比必要的更加困难:

  • check_list被定义为数组(不是集合)。数组按位置索引。要检查列表中是否包含值,您需要 iterate 。通常,仅构造集并测试成员资格/交集/差异/等通常更容易。

  • aws_valid_sgs规则从输入中构造了一堆不必要的中间值(例如dockey_idsresource等)是输入中的SG集合,可以通过2条语句来计算:在启动配置中查找键以security_group.开头的字段,并为这些键构造一组字段值。