1

I have written a OPA policy that creates the following output:

[
   
    {
        "permission": [
            "module:get",
            "workflow:get",
            "ruletable:get"
        ],
        "resource": "folder-2"
    },
    {
        "permission": [
            "module:get",
            "workflow:get",
            "ruletable:get"
        ],
        "resource": "proj-1"
    },
    {
        "permission": [
            "module:get",
            "workflow:get",
            "ruletable:get",
            "module:write",
            "workflow:write",
            "ruletable:write"
        ],
        "resource": "folder-2"
    }

The thing is in my structure, the object as I you can see the might have duplicate resource key. And I only want one unique resource key with the permission being the union of all permissions for that resource key. Been fiddling this for a whole day, still couldn't figure it out.

how to manipulate this resource structure using OPA rego?

Swan2017
  • 11
  • 2

1 Answers1

0

I had a similar requirement and could serve it with below policy using a has_key function which checks if there are duplicate entries and then add it to the existed object bucket.

Input,

x = {"a":[true], "b":["foo"], "c":[4]}
y = {"b":["bar"], "d":["du"], "c":[100]}

expected output

{"a": [true],"b": ["bar","foo"],"c": [100,4],"d": ["du"]}

Policy

package app.merge

import future.keywords.in

example {
x = {"a":[true], "b":["foo"], "c":[4]}
y = {"b":["bar"], "d":"du", "c":[100]}

merge_arrays(x,y) == {"a": [true],"b": ["bar","foo"],"c": [100,4],"d": "du"}
}

has_key(x, k) { _ = x[k] }

merge_values(k, a, b) = a[k]{
not has_key(b, k)
}

merge_values(k, a, b) = b[k]{
not has_key(a, k) 
}

merge_values(k, a, b) = c{
has_key(a, k) 
has_key(b, k)
c := array.concat(a[k],b[k])
}

merge_arrays(a, b) = c {
    ks := {k | some k; _ = a[k]} | {k | some k; _ = b[k]}
    c := {k: v | some k; ks[k]; v := merge_values(k, b, a)}
}

Playground link https://play.openpolicyagent.org/p/EUCS5ynfqt

Hope you can use the same approach with has_key function and merge the objects.

Original inspiration shared at https://medium.com/@pushpalanka/hands-on-with-opa-2-merging-objects-de4f26d96baf

Pushpalanka
  • 857
  • 1
  • 8
  • 20