Skip to main content

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.

policy.rego
package play

import rego.v1

default allow := false

allow if input.admin == true

allow if {
input.path[0] == "users"
input.path[1] == input.user
}
input.json
{
"roles": [
"admin"
],
"path": "/"
}
data.json
{}

Open in OPA Playground

RuleOutput Value
allowfalse

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.

policy.rego
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)
}
input.json
{
"amount": 3000,
"role": "staff"
}
data.json
{
"overrides": {
"staff": 10000
}
}

Open in OPA Playground

RuleOutput ValueNotes
allowtrueSince the request is from staff, the request is allowed.