如何在Rego规则中使用参数?我会有这样的东西:
deny[reason] {
input.request.kind.kind == "Route"
not valid_route_request[label]
reason := sprintf("missing or wrong router selector label: %v", [label])
}
valid_route_request[label] {
requester := input.request.userInfo.username
some i # iterate on all users
requester == data.kubernetes.users[i].metadata.name
label := input.request.object.metadata.labels["router-selector"]
label == data.kubernetes.users[i].metadata.annotations[router_selector_key]
}其中使用label构建错误消息。我从OPA那里得到错误: var标签不安全..。
一般来说,我还不清楚如何在Rego中传递参数。
发布于 2020-05-05 11:23:38
你的例子几乎是正确的--你面临的问题是label是“不安全的”。
在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”也将包含,因此.)
https://stackoverflow.com/questions/61578607
复制相似问题