opaopen-policy-agent

how to control/sanitise Open Policy Agent (OPA) response


I have the following policy working just fine but its response feels a bit dirty. I am only interested in the allow and permissions keys.

package example 
default allow = false

getUserPermissions(user) = userpermission {
    allowed_list := {"users": {
        "a": {"permissions": [
            "app.write",
            "app.approve",
            "app.read",
        ]},
        "b": {"permissions": [
            "app.write",
            "app.read",
        ]},
    }}
    userpermission = allowed_list.users[user].permissions
}

has_any_privilege(x_arr) {
    uid := input.user
    permissions := getUserPermissions(uid)
    permissions[_] == x_arr[_]
}

default approve = false
approve {
    has_any_privilege({"app.approve"})
}

default write = false
write {
    has_any_privilege({"app.write"})
}

default read = false
read {
    has_any_privilege({"app.read", "app.write", "app.approve"})
}

allow {
    has_any_privilege({"app.read"})
}


permissions := {
    "approve": approve,
    "write": write,
    "read": read,
}

when I use the following input:

{"user": "b"}

the response is

{
    "allow": true,
    "approve": false,
    "permissions": {
        "approve": false,
        "read": true,
        "write": true
    },
    "read": true,
    "write": true
}

the read, write, approve are kind of helper rules I created to be able to build the permissions key correctly.

How can I restrict the response to contain just the allow and permissions keys?

Here is the above example in opa playground


Solution

  • The Rego Playground evaluates the entire package, which is why you’re seeing all the rules in the output. When you’re running OPA as a server, you’d normally only query one specific rule for evaluation, e.g /v1/data/example/allow

    You can do that in the playground too by selecting the allow rule, which will change the Evaluate button to “Evaluate Selection”.