Rego: Iteration, Sets & Functions
Real policies walk lists of containers, resources and rules. Rego has three tools for that: some … in ("there exists"), every … in ("for all") and comprehensions (build a collection). Combined with sets and built-in functions they cover almost every policy you will write.
| Form | Meaning |
|---|---|
some c in input.containers |
for some element c (the body is tried for each) |
some i, c in input.containers |
with its index (or key, for objects) |
every c in input.containers { … } |
the body holds for all elements (true for an empty list) |
{c.name | some c in xs; c.privileged} |
set comprehension |
[x | …], {k: v | …} |
array and object comprehensions |
a - b, a & b, a | b |
set difference, intersection, union |
object.get(obj, "key", default) |
safe lookup with a default |
A policy for linkly's Deployment
mkdir p && cd p
cat > deployment.rego <<'REGO'
package k8s.deployment
containers := input.spec.template.spec.containers
# for every container: limits must be set
all_limited if {
every c in containers {
c.resources.limits.memory
}
}
deny contains msg if {
not all_limited
missing := [c.name | some c in containers; not c.resources.limits.memory]
msg := sprintf("containers without a memory limit: %v", [missing])
}
# there exists a privileged container
deny contains msg if {
some c in containers
c.securityContext.privileged
msg := sprintf("container %q is privileged", [c.name])
}
# required labels: set difference
required_labels := {"app.kubernetes.io/name", "team"}
deny contains msg if {
missing := required_labels - {k | some k, _ in input.metadata.labels}
count(missing) > 0
msg := sprintf("missing labels: %v", [sort(missing)])
}
# duplicate container ports, with an index-based loop
deny contains msg if {
ports := [p.containerPort | some c in containers; some p in c.ports]
some i, p in ports
some j, q in ports
i < j
p == q
msg := sprintf("container port %d is declared twice", [p])
}
# a helper function with a default, and a regex
deny contains msg if {
some c in containers
not pinned(c.image)
msg := sprintf("image %s must be pinned to a version or digest", [c.image])
}
pinned(image) if regex.match(`@sha256:[a-f0-9]{64}
Rego: Iteration, Sets & Functions - Secrets & Policy as Code: Vault, SOPS, OPA & Conftest · ExcelTAD
, image)
pinned(image) if {
tag := split(image, ":")[1]
tag != "latest"
}
REGO
cat > linkly.json <<'JSON'
{"kind": "Deployment",
"metadata": {"name": "linkly", "labels": {"app.kubernetes.io/name": "linkly"}},
"spec": {"template": {"spec": {"containers": [
{"name": "app", "image": "ghcr.io/acme/linkly:1.4.2",
"ports": [{"containerPort": 8080}],
"resources": {"limits": {"memory": "256Mi"}}},
{"name": "debug", "image": "busybox",
"ports": [{"containerPort": 8080}],
"securityContext": {"privileged": true}}
]}}}}
JSON
opa eval -d deployment.rego -i linkly.json -f pretty 'data.k8s.deployment.deny'[
"container \"debug\" is privileged",
"container port 8080 is declared twice",
"containers without a memory limit: [\"debug\"]",
"image busybox must be pinned to a version or digest",
"missing labels: [\"team\"]"
]
Read the rules aloud and they are close to English:
not all_limited: "it is not the case that every container has a memory limit". Rego doesn't allownot every …directly (illegal negation of 'every'), so theeverygoes into a helper rule that is negated.required_labels - {k | some k, _ in input.metadata.labels}: the set of required labels minus the set of present label keys.- The port rule loops twice over the same list with
i < j, which finds each duplicate pair once. pinnedhas two definitions (OR): a digest, or a tag that isn'tlatest. Forbusybox,split(image, ":")[1]is undefined, so neither definition holds andnot pinned(...)is true.
Comprehensions for reports
Rules don't have to deny. Comprehensions build summaries that other rules, or people, use:
cat > summary.rego <<'REGO'
package summary
images := {c.image | some c in input.spec.template.spec.containers}
by_registry[registry] := names if {
some c in input.spec.template.spec.containers
registry := split(c.image, "/")[0]
names := [d.name | some d in input.spec.template.spec.containers; startswith(d.image, registry)]
}
total_memory_mib := sum([to_number(trim_suffix(c.resources.limits.memory, "Mi")) |
some c in input.spec.template.spec.containers])
REGO
cat > d.json <<'JSON'
{"spec": {"template": {"spec": {"containers": [
{"name": "app", "image": "ghcr.io/acme/linkly:1.4.2", "resources": {"limits": {"memory": "256Mi"}}},
{"name": "proxy", "image": "ghcr.io/acme/envoy:1.36", "resources": {"limits": {"memory": "128Mi"}}},
{"name": "log", "image": "docker.io/fluent/fluent-bit:4.1", "resources": {"limits": {"memory": "64Mi"}}}
]}}}}
JSON
opa eval -d summary.rego -i d.json -f pretty 'data.summary'{
"by_registry": {
"docker.io": [
"log"
],
"ghcr.io": [
"app",
"proxy"
]
},
"images": [
"docker.io/fluent/fluent-bit:4.1",
"ghcr.io/acme/envoy:1.36",
"ghcr.io/acme/linkly:1.4.2"
],
"total_memory_mib": 448
}
by_registry[registry] := names is a partial object rule: it builds an object with one key per value of registry that satisfies the body.
Useful built-ins
| Built-in | Example |
|---|---|
| strings | startswith, endswith, contains, split, concat, lower, sprintf, trim_suffix |
| matching | regex.match, glob.match("*.acme.internal", ["."], host) |
| collections | count, sum, max, sort, array.concat, object.get, object.union, json.patch |
| units and time | units.parse_bytes("256Mi"), units.parse("500m"), time.parse_rfc3339_ns |
| encoding | base64.decode, yaml.unmarshal, json.unmarshal |
| net | net.cidr_contains("10.0.0.0/8", ip), net.cidr_is_valid |
| crypto/JWT | io.jwt.decode, io.jwt.verify_rs256 |
opa eval with a literal query is the quickest way to try one: opa eval 'units.parse_bytes("256Mi")'.
Test yourself
What does every c in containers { c.resources.limits.memory } return for an empty list of containers?
- false
- true
- undefined
- An error
How do you get the set of label keys that are required but missing?
required & presentrequired - presentpresent - requiredrequired | present
Two definitions of a function pinned(image) exist. When is pinned(x) true?
- When both hold
- When either holds
- Never; functions can't have two definitions
- Only the first counts