TExcelTAD

Rego Basics with opa eval

Rego is a query language over JSON, closer to SQL or Datalog than to Python. A rule body is a list of conditions, all of which must hold; a rule is "defined" only if some way of satisfying its body exists. There are no loops in the usual sense: you state what must be true, and OPA searches.

The building blocks

rego
package linkly.authz              # every file has a package; rules live at data.linkly.authz.<rule>

default allow := false            # value when no other definition applies

allow if {                        # complete rule: allow is true if ALL conditions hold
	input.method == "GET"
	input.path[0] == "links"
}

allow if {                        # a second definition: OR between bodies
	input.user.role == "admin"
}

deny contains msg if {            # partial set rule: collects every msg that satisfies the body
	input.method == "DELETE"
	not input.user.role == "admin"
	msg := sprintf("%s may not delete", [input.user.name])
}
  • Conditions on separate lines are AND; separate rule definitions with the same name are OR.
  • := assigns a local variable; == compares; = unifies (rarely needed).
  • input is the document being checked; data holds loaded policies and JSON/YAML data files.
  • A reference into a missing field (input.user.role when there is no user) is undefined, which makes the condition fail quietly rather than throw an error. not turns undefined into true.

Evaluating with opa eval

bash · try it yourself
mkdir authz && cd authz
cat > authz.rego <<'REGO'
package linkly.authz

default allow := false

allow if {
	input.method == "GET"
	input.path[0] == "links"
}

allow if input.user.role == "admin"

deny contains msg if {
	input.method == "DELETE"
	not input.user.role == "admin"
	msg := sprintf("%s may not delete", [input.user.name])
}
REGO
echo '{"method": "GET", "path": ["links", "abc123"], "user": {"name": "ada", "role": "viewer"}}' > get.json
echo '{"method": "DELETE", "path": ["links", "abc123"], "user": {"name": "ada", "role": "viewer"}}' > delete.json
echo '{"method": "DELETE", "path": ["links", "abc123"], "user": {"name": "grace", "role": "admin"}}' > admin.json

for f in get delete admin; do
  printf '%-7s allow=%s deny=%s\n' $f \
    "$(opa eval -d authz.rego -i $f.json -f raw 'data.linkly.authz.allow')" \
    "$(opa eval -d authz.rego -i $f.json -f raw 'data.linkly.authz.deny')"
done
echo "--- the whole package as one JSON document"
opa eval -d authz.rego -i delete.json -f raw 'data.linkly.authz'
echo "--- an ad-hoc query, like a REPL"
opa eval -i delete.json -f raw 'upper(input.method) == "DELETE"'
get     allow=true deny=[]
delete  allow=false deny=["ada may not delete"]
admin   allow=true deny=[]
--- the whole package as one JSON document
{"allow":false,"deny":["ada may not delete"]}
--- an ad-hoc query, like a REPL
true
  • -d loads policy and data files (or whole directories), -i the input, and the last argument is the query.
  • -f raw prints just the value; the default -f json wraps it in a result envelope with expressions and locations, useful for tools but noisy for people. -f pretty is in between.

Undefined, false and default

The difference between false and undefined is the most common Rego surprise:

bash · try it yourself
cat > u.rego <<'REGO'
package demo

is_admin if input.user.role == "admin"

default is_admin_d := false

is_admin_d if input.user.role == "admin"
REGO
echo '{"user": {"role": "viewer"}}' > in.json
echo "is_admin:   $(opa eval -d u.rego -i in.json -f raw 'data.demo.is_admin')"
echo "is_admin_d: $(opa eval -d u.rego -i in.json -f raw 'data.demo.is_admin_d')"
opa eval -d u.rego -i in.json -f json 'data.demo.is_admin' | jq -c .
echo "--- --fail-defined: exit 1 if the query produced a value (useful in scripts)"
opa eval --fail-defined -d u.rego -i in.json 'data.demo.is_admin_d == false' > /dev/null; echo "exit $?"
is_admin:
is_admin_d: false
{}
--- --fail-defined: exit 1 if the query produced a value (useful in scripts)
exit 1

Without a default, a rule whose conditions fail has no value at all: -f raw prints nothing and the JSON result is empty. Always give boolean decisions a default, or callers will see "nothing" and have to guess.

Data next to policy

Lists that change more often than logic (approved registries, team owners, exceptions) belong in data files, loaded with -d and reachable under data:

bash · try it yourself
cat > registries.rego <<'REGO'
package images

deny contains msg if {
	some c in input.spec.containers
	not approved(c.image)
	msg := sprintf("image %s is not from an approved registry", [c.image])
}

approved(image) if {
	some prefix in data.config.approved_registries
	startswith(image, prefix)
}
REGO
cat > config.json <<'JSON'
{"config": {"approved_registries": ["ghcr.io/acme/", "registry.acme.internal/"]}}
JSON
cat > pod.json <<'JSON'
{"kind": "Pod", "spec": {"containers": [
  {"name": "app", "image": "ghcr.io/acme/linkly:1.4.2"},
  {"name": "debug", "image": "docker.io/library/busybox:1.37"}
]}}
JSON
opa eval -d registries.rego -d config.json -i pod.json -f pretty 'data.images.deny'
[
  "image docker.io/library/busybox:1.37 is not from an approved registry"
]

approved(image) is a function: a rule with arguments. some prefix in … iterates; the next lesson covers iteration properly.

Test yourself

Two allow if { … } definitions exist. When is allow true?

  1. When both bodies hold
  2. When at least one body holds (definitions are OR-ed)
  3. Never; duplicate names are errors
  4. Only for the last definition

A rule without default has failing conditions. What does opa eval -f raw print?

  1. false
  2. Nothing: the rule is undefined
  3. null
  4. An error

Where should a list of approved registries live?

  1. Hard-coded in each rule
  2. In a data file loaded with -d, read through data.…
  3. In the input
  4. In an environment variable