Rego Keyword: default
The default
keyword is used to provide a default value for rules and
functions. If in other cases, a rule or function is not defined, the default
value will be used.
It is often helpful to have know that a value will always be defined so that policy or callers do not also need to handle undefined values.
Examples
Denying by default
When default deny behavior is required, knowing that a value will never be undefined is helpful. This is common in access control systems where access is denied unless explicitly allowed.
In the following example, the policy's allow rules depend on fields in input
.
If any field is missing, allow
should return false instead of undefined. This
is achieved using the default
keyword.
The policy handles unexpected data formats, ensuring the result is always a boolean.
package play
import rego.v1
default allow := false
allow if input.admin == true
allow if {
input.path[0] == "users"
input.path[1] == input.user
}
{
"roles": [
"admin"
],
"path": "/"
}
{}
Rule | Output Value |
---|---|
allow | false |
Creating an override function
As we saw in the previous example, default
is helpful for handling undefined
values. Handling undefined values is not just important for callers, but also
within policies themselves.
Using the default
keyword with functions, we can quickly build in
functionality to set a base case that's overridden when conditions are met.
package play
import rego.v1
default max_amount(_, _) := 1000
max_amount(overrides, role) := overrides[role]
allow if {
input.amount <= max_amount(data.overrides, input.role)
}
{
"amount": 3000,
"role": "staff"
}
{
"overrides": {
"staff": 10000
}
}
Rule | Output Value | Notes |
---|---|---|
allow | true | Since the request is from staff, the request is allowed. |