Open Policy Agent (OPA) Rego - 在运行时访问输入对象嵌套字段

Open Policy Agent (OPA) Rego - Accessing Input Object Nested Fields At Runtime

我正在尝试创建一个有点通用的 rego 策略,它可以评估从输入中给出的嵌套对象字段。 例如:

field_from_input := "spec.securityContext.runAsRoot"

violation[{"msg": msg}] {
  fields := split(field_from_input, ".")
  # Somehow get the inner "runAsRoot" field value
  nested_value := input.object[fields]
  nested_value == "test"
  msg := "some message..."
}

我试过使用内置的“object.filter”和“json.filter”函数,但它们似乎不适用于嵌套属性。 我也试过用“。”分割属性路径。并以某种方式按字段迭代对象,但没有成功。

任何帮助将不胜感激。

这似乎是 walk built-in 的一个好案例。使用它来遍历对象允许您检查路径 and/or 值以匹配您可能希望的任何条件。

package play

spec := {
    "securityContext": {
        "runAsRoot": true,
    },
}

violation[{"msg": msg}] {
    walk(spec, [path, value])
    node := path[count(path) - 1]
    
    node == "runAsRoot"
    value == true

    msg := "some message..."
}

查看游乐场示例 here