[英]How to create OPA rego policy for a whitelist?
我正在尝试在 OPA rego 中实施白名单策略。 该策略的目的是阻止除已列入白名单的属性之外的所有属性。 但是,我无法让它工作。
这是我的 rego 政策:
package play
whitelisted_attributes =
{
"foo.bar",
"hello.from.*.world"
}
default allow = false
default not_in_whitelist = true
not_in_whitelist {
whitelisted := {attr | attr := input.attributes[_]; glob.match(whitelisted_attributes[_], ["."], attr)}
count(whitelisted) == 0
}
allow {
not not_in_whitelist
}
这是我的输入:
{
"attributes": [
"foo.bar"
]
}
这是根据 Rego Playground 的 output:
{
"allow": false,
"not_in_whitelist": true,
"whitelisted_attributes": [
"foo.bar",
"hello.from.*.world"
]
}
如您所见,“允许”应该为真,因为在白名单中找到了输入。 此外,“not_in_whitelist”应该为假,因为输入属性在白名单中。
这里发生的情况是,由于其中一个元素在白名单中,因此not_in_whitelist
规则将评估为未定义(因为这是不满足所有条件的规则的评估结果)。
由于not_in_whitelist
评估为未定义,规则将被分配默认值true
:
default not_in_whitelist = true
然后允许规则将在not
检查中反转它,使规则失败(因为not true
== false
):
allow {
not not_in_whitelist
}
我建议简单地删除not_in_whitelist
的默认分配。
感谢@Devoops 的提示。 我回到了 Rego Playground,经过多次尝试和错误,我想出了一个可行的政策。 我在这里为有类似需求的其他人发布它。
package play
default allow = false
default in_whitelist = false
whitelist =
{
"foo.bar",
"hello.from.*.world"
}
num_attributes := count(input.attributes)
in_whitelist {
glob.match(whitelist[_], ["."], input.attributes[_])
}
not_in_whitelist = result {
num_attributes == 1
result := (in_whitelist == false)
}
not_in_whitelist = result {
num_attributes > 1
whitelisted := {attr | attr := input.attributes[_]; glob.match(whitelist[_], ["."], attr)}
result := (count(whitelisted) < num_attributes)
}
allow {
not not_in_whitelist
}
deny[msg] {
not_in_whitelist
msg = sprintf("You are only allowed to modify the following whitelisted attributes: %v", [whitelist])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.