您的示例几乎是正确的-您面临的问题label
是“不安全”。
TLDR;label
在deny
规则内分配:
deny[reason] {
input.request.kind.kind == "Route"
label := input.request.object.metadata.labels["router-selector"]
not valid_route_request[label]
reason := sprintf("wrong 'router-selector' label: %v", [label])
}
deny[reason] {
input.request.kind.kind == "Route"
not input.request.object.metadata.labels["router-selector"]
reason := "missing 'router-selector' label"
}
请注意,我创建了两个拒绝规则。一种用于路径input.request.object.metadata.labels["route-selector']
未定义的情况,另一种用于无效值的情况。
为什么 OPA 在原始示例中会生成安全错误?安全性是 Rego 的一个属性,它确保可以为所有变量分配有限数量的值。要被认为是“安全的”,变量必须作为至少一个非否定表达式的输出出现。
以下是一些安全的示例:
# 'a' is assigned to the value referenced by input.foo
a := input.foo
# 'x' is assigned to the keys of the collection referenced by input.foo
input.foo[x]
# 'label' is is assigned to the keys of the collection referenced by valid_route_request
valid_route_request[label]
# 'x' is safe because it is assigned outside the negated expression
x := 7; not illegal_numbers[x]
以下是不安全表达式的示例:
# 'x' is unsafe because it does not appear as an output of a non-negated expression
not p[x]; not q[x]
# 'y' is unsafe because it only appears as a built-in function input
count(y)
出现在规则头部的变量也可能发生安全错误:
# 'msg' is unsafe because it is not assigned inside the body of the rule.
deny[msg] {
input.request.kind.kind == "BadKind"
}
安全性很重要,因为它确保 OPA 可以枚举所有可以分配给变量的值。如果变量不安全,则意味着可能有无限数量的变量赋值。在您的示例中,该语句valid_route_request
生成一组值(标签?)。规则中的not valid_route_request[label]
语句deny
是不安全的,因为label
没有在规则的其他地方分配deny
(并且label
可能不会出现在全局范围中。)如果您在拒绝规则中包含“一些”,这实际上会变得更清楚一些:
deny[reason] {
some label
input.request.kind.kind == "Route"
not valid_route_request[label]
reason := ...
}
这条规则说(英文):
reason is in deny if for some label, input.request.kind.kind equals Route and label is not in valid_route_request, and ...
从技术上讲,将有无限数量的分配来label
满足此规则(例如,字符串“12345”不会包含在valid_route_request
其中,“123456”也不会包含在内......)