6

I want to use an OR operation to combine the following conditions:

  • the count of my arr is not equal to 0
  • my email does not contain "test.com"

Currently I am using the built-in function any():

any([count(arr) != 0, not contains(email, "test.com")])

However my rule is producing an error.

How can I achieve and improve this in one line?

1
  • See also the related issue #3239 which suggests alternatives to any(). Commented Oct 19, 2022 at 19:18

3 Answers 3

10

More generally, Rego does not allow OR-ing statements in the same function. Using any() works well for simple cases, but can become unwieldy for complex ones so it is considered an antipattern.

Instead, Rego uses incremental rules, where every statement within each Rule is AND-ed together, and rules of the same name are OR-ed together.

Consider the following deny rule. In short, it says that we will deny the request if at least one of:

  1. The user is not an admin, or
  2. Today is Sunday.
deny {
    input.role != "admin"
}

deny {
    time.weekday(time.now_ns()) == "Sunday"
}

This would only allow requests to the admin role on days other than Sunday. If instead we said:

deny {
    input.role != "admin"
    time.weekday(time.now_ns()) == "Sunday"
}

We would then only deny requests from non-admin roles on Sunday. Requests from admin would always be allowed.

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

1 Comment

That’s a useful addition!
3

The not keyword is a bit of a special case in that it can't be used inside of many contexts such as the array of your example. I believe this could be improved in OPA, but until then you can trivially avoid it for at most cases, like the one you provided:

any([count(arr) != 0, contains(email, "test.com") == false])

Comments

0

Actually I arrived here because I was trying to do the following:

not (role == "analyst" or stream == "analysis")

Turns out that's not possible. But some basic symbolic logic (De Morgan's Law)

¬(X or Y) == ¬X and ¬Y

Thanks to Will's answer above about incremental rules, the obvious answer to this was:

not role == "analyst"
not stream == "analysis"

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.