Rego规则中的参数[Open Policy Agent]

时间:2020-05-03 17:15:01

标签: open-policy-agent rego

如何在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中传递参数。

1 个答案:

答案 0 :(得分:2)

您的示例几乎是 是正确的-您面临的问题是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不会出现在全局范围内。)如果您在“拒绝”规则中添加“ some”,则实际上会变得更加清晰:

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”也会包含)。 ..)