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?

1
  • Can you share your policy as well? A playground link would be great. Commented Feb 21, 2023 at 9:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.