Rego Keyword Examples: every
Rego rules and statements are existentially quantified by default. This means
that if there is any solution then the rule is true, or a value is bound. Some
policies require checking all elements in an array or object. The every
keyword makes this
universal quantification
easier.
Here we show two equivalent rules achieve universal quantification, note how
much easier to read the one using every
is.
package play
allow1 if {
every e in [1, 2, 3] {
e < 4
}
}
# without every, don't do this!
allow2 if {
{r | some e in [1, 2, 3]; r := e < 4} == {true}
}
allow2
works by generating a set of 'results' testing elements from the
array [1,2,3]
. The resulting set is tested against {true}
to verify all
elements are true
. As we can see every
is a much better option!
Examples
Checking every feature flag
Here we use the every
keyword to validate that an example session has all the
required feature flags for a request.
test_speedy_checkout
is false in the input.json
, this will need to be true
for the user to be allowed to load the new checkout page.
package play
default allow := false
allow if {
input.path == "/new/checkout"
every feature in new_checkout_features {
input.features[feature] == true
}
}
new_checkout_features := {
"new_ui",
"test_speedy_checkout",
}
{
"features": {
"new_ui": true,
"test_speedy_checkout": false
},
"path": "/new/checkout",
"email": "alice@example.com"
}
{}
Enforcing meeting invite rules
Every can also be used to check an object's keys and values. Here we do just that to validate attendees of a meeting invite.
In this example, all attendees must have the staff role and the correct email address suffix for the meeting to be created.
Update Bob to have staff
and you should see it's possible to create
the invite.
package play
default allow := false
allow if {
every email, user in input.invites {
endswith(email, "@example.com")
"staff" in user.roles
}
}
{
"invites": {
"bob@example.com": {
"roles": [
"contractor"
]
},
"charlie@example.com": {
"roles": [
"staff"
]
}
},
"owner": "alice@example.com"
}
{}