OPA规则体中的Assignment(=)运算符和Equality(==)运算符有什么区别



在OPA文档中https://www.openpolicyagent.org/docs/latest/policy-testing/有一个政策定义如下:


allow {
input.path == ["users"]
input.method == "POST"
}
allow {
some profile_id
input.path = ["users", profile_id]
input.method == "GET"
profile_id == input.user_id
}

在第一条规则中,它是input.path=["users"],而在第二条规则中它是input.path=["user",profile_id]

Rego中的赋值运算符是:===用于比较,=运算符用于统一。有一节描述了文档中的差异,但简单地说,统一结合了赋值比较,因此在您的示例中,假设input.path有两个元素,则第二个元素值将分配给profile_id

如果你想的话,可以写这个策略来分割比较和分配:

allow {
count(input.path) == 2
input.path[0] == "users"
profile_id := input.path[1]
input.method == "GET"
profile_id == input.user_id
}

可以说这有点混乱。然而,统一应谨慎使用,因为在大多数其他情况下,将分配与比较区分开来更为明确。

在这种特殊情况下,如果您跳过profile_id:的中间分配,您甚至可以仅使用比较

allow {
input.path == ["users", input.user_id]
input.method == "GET"
}

最新更新