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

1.4k views Asked by At

I am trying to create a somewhat generic rego policy that can evaluate a nested object field that is given from an input. For example:

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..."
}

I've tried using the built in "object.filter" and "json.filter" function but they don't seem to work for nested attributes. I've also tried splitting the attribute path by "." and somehow iterate the object by the fields, but had no success.

Any help will be much appreciated.

1

There are 1 answers

0
Devoops On BEST ANSWER

This seems like a good case for the walk built-in. Using that to traverse the object allows you to check both the path and/or the value to match any conditions you may wish for.

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..."
}

See playground example here.