Builtins: pure, provided and impure

An engine gets its builtins as a value, and each builtin has one of three kinds: pure, provided or impure. The kind shows if a query can give the same result again. This page also explains how rego4k reads JSON and YAML.

The engine has no builtins of its own

Core has no builtins, not even == or +. In Rego, operators are calls of builtins (a + b is plus(a, b)), and the engine treats all of them in the same way.

You give an engine its builtins as a Builtins value:

Engines.kt
// the pure builtins of OPA's library, with OPA's regex engine
Rego.standard(Re2Engine)
// java.util.regex: no dependency, but it differs from OPA
Rego.standard(JavaRegexEngine)
// and the provided builtins (rego4k-builtins-stdlib-provided)
Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.Provided.stdlib)
// and the impure builtins (rego4k-builtins-stdlib-impure)
Rego(
    Builtins.Pure.stdlib(Re2Engine) +
        Builtins.Provided.stdlib +
        Builtins.Impure.stdlib,
)
// all the builtins of OPA's library (rego4k-builtins-stdlib)
Rego(Builtins.stdlib(Re2Engine))
// and one of your own
Rego(
    Builtins.Pure.stdlib(Re2Engine) +
        Builtin.Pure("hello", 1) { args -> Str("hello ${args.str(0)}") },
)
// only your own
Rego(
    Builtins.of(
        Builtin.Pure("pick", 3) { args -> if (args.bool(0)) args[1] else args[2] },
    ),
)
Engines.kt, lines 20 to 44, on GitHub

An engine can also get fewer builtins. Builtins.only keeps the builtins with the given names. For example, a shaken bundle lists the builtins that its rules can call (see rego4k-bundles-core):

OnlyBuiltins.kt
val shaken = bundle.shake(
    Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.yaml),
    "authz/allow",
)
val rego = Rego(
    (Builtins.Pure.stdlib(Re2Engine) + Builtins.yaml).only(shaken.builtins),
)
OnlyBuiltins.kt, lines 14 to 20, on GitHub

The standard library is not privileged. rego4k-builtins-stdlib-pure uses only the public API of core. Thus a builtin that you write can do everything that a standard builtin can do.

To change a standard builtin, add one with the same name. The later builtin replaces the earlier one.

A builtin is pure, provided or impure

Some builtins read more than their arguments. Compare these three rules:

kinds.rego
# reads the time of the query
expired if time.now_ns() > input.token.exp * 1000000000
# also reads the time zone data
late if time.clock([time.now_ns(), "America/Mexico_City"])[0] >= 18
# reads a random value
ticket := uuid.rfc4122("ticket")
kinds.rego, lines 4 to 9, on GitHub

The time. A year later, an auditor evaluates expired again with the same token, and gets true. On the day of the decision, the token was valid. But the runtime gave the query its time. If the decision recorded that time, the runtime can give the same time again, and the auditor gets the result of that day.

The time zone data is similar. In 2022 Mexico stopped daylight saving time, and the rules of America/Mexico_City changed in the next release of the data. Thus late can give a different result for the same instant.

The runtime cannot give old data again, but it can record the version that it read, for example 2026e. An auditor with the same version gets the same result. An auditor with a different version learns why the result can differ.

Randomness. ticket is different. The values that come from a random seed depend on the algorithm and on the order of the calls, and a new version of rego4k or of the JVM can change both. Thus a recorded seed does not give the same ticket again.

The network is different too. http.send calls a server, and the server can give another answer tomorrow. The runtime cannot give that answer again.

Thus each builtin has one of three kinds. The kind is a type, so the compiler shows it to a reader:

Each kind is in its own module, so the dependencies of an application show the kinds that it uses:

Engines.kt
// time.now_ns() fails: add Builtins.Provided.stdlib
Rego.standard(Re2Engine)
// the results can be reproduced
Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.Provided.stdlib)
// OPA's library, without the yaml.* builtins
Rego(
    Builtins.Pure.stdlib(Re2Engine) +
        Builtins.Provided.stdlib +
        Builtins.Impure.stdlib,
)
// rejects each impure builtin when the builtins are registered
Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.Provided.stdlib, pure = true)
Engines.kt, lines 51 to 62, on GitHub

Builtins.Pure.stdlib(regex) has a pure version of each builtin that reads a provided value only for some arguments. For example, time.date(0) and time.parse_ns("RFC3339", "2026-01-15T09:00:00+02:00") work, because UTC and a fixed offset need no time zone data.

But time.date([0, "Europe/Paris"]) fails with the message time zone "Europe/Paris" needs the time zone data: add Builtins.Provided.stdlib.

Rego takes the providers, so that a test can fix each provided value. The time zone data comes from the JVM. A Rego cannot replace it, because the rules of each zone come from the JVM:

Providers.kt
val rego = Rego(
    Builtins.Pure.stdlib(Re2Engine) + Builtins.Provided.stdlib,
    // the time of each query
    clock = InstantSource.fixed(Instant.parse("2026-01-15T09:00:00Z")),
    // the zone of "Local"
    localZone = ZoneId.of("Europe/London"),
    // the value of opa.runtime
    runtime = Obj.of("env" to Obj.EMPTY),
)
val result = rego.compile(modules).prepare("data.authz.late").result(input)
// the time 2026-01-15T09:00:00Z, and the version of the zone data,
// for example 2026e
val provided = result.provided
// false
val impure = result.calledImpureBuiltin
Providers.kt, lines 30 to 44, on GitHub

The version of the time zone data is the version that the JVM gives (ZoneRulesProvider.getVersions), for example 2026e. We chose it because the JVM supplies the rules of each zone, so its version names exactly the rules that the query used.

The zone abbreviations come from the files of the host, as in Go, and this version does not cover them.

The kinds protect you from mistakes. They cannot stop a builtin that is written to break them:

The results are the same as OPA's

A policy must give the same decision in rego4k and in OPA. Teams test policies with opa test, and those tests must prove something about production.

Thus rego4k copies the behaviour of Go and OPA where it is visible to a policy:

The conformance suite is the test of this. ./gradlew test downloads it and runs all of its cases, with the full library Builtins.stdlib(Re2Engine).

Without Builtins.Provided.stdlib and Builtins.Impure.stdlib, a pure builtin fails where OPA's result depends on the time, the time zone data or randomness (see A builtin is pure, provided or impure).

A query result can be reproduced

The problem: the same question, a different answer

Six months after a decision, an auditor asks why the policy allowed Alice to read a document. You have the policy, the input and the data of that day. You evaluate the query again, and the policy now denies her.

Nothing is wrong with the policy. The query read something that is not in the input:

questions.rego
# the clock moved on
token_valid if time.now_ns() < input.token.exp * 1000000000

# the rota changed
on_call if http.send({
	"method": "GET",
	"url": "https://rota.example/today",
}).body.on_call

# the time zone data changed
working_hours if time.clock([time.now_ns(), "Europe/London"])[0] < 18
questions.rego, lines 4 to 14, on GitHub

A test has the same problem. A test of token_valid passes today and fails next month, when the token in the test has expired. The test did not find a fault. It only ran on a different day.

If the same question can give a different answer, a failed test gives you no information, and the auditor cannot learn why Alice got access.

Some inputs can be given again, and some cannot

The time of a query is an input, like input itself. If the application gives the query a fixed time, time.now_ns gives the same value each time, and token_valid above is reproducible. OPA already gives each query one time: all calls of time.now_ns in a query give the same value.

The time zone data. working_hours reads the time zone data. The runtime cannot give old data again, but the query can record the version that it read.

The local zone of "Local" and the value of opa.runtime are inputs like the time: the runtime can give them again. These are the provided values (see A builtin is pure, provided or impure).

The network. on_call is different. The rota server can give a different body tomorrow, and the runtime cannot give the body of today again.

Randomness. A random value cannot be given again either: uuid.rfc4122 gives a different UUID in each query.

The query records the provided values that it read

Prepared.result gives the solutions, the provided values that the query read, and whether the query called an impure builtin. A value that the query did not read is null:

Providers.kt
val result = policy.prepare("data.authz.token_valid").result(input, data)
// the time 2026-01-15T09:00:00Z
val provided = result.provided
// false
val impure = result.calledImpureBuiltin
val again = policy.prepare("data.authz.token_valid")
    .result(input, data, timestamp = Instant.parse("2026-01-15T09:00:00Z"))
// the same solutions, on any day
Providers.kt, lines 57 to 64, on GitHub

A test of token_valid gives a Rego with a fixed time (clock = InstantSource.fixed(...)), and passes on any day. The x509 builtins also verify a certificate at that time.

The conclusion: what to store

To reproduce the result of a query that called no impure builtin, store these items:

With these items, the auditor gets the same answer six months later. If the JVM of the auditor has other time zone data, Decision.reproduce refuses, and its message names the version that the decision read.

Signed decisions store these items for you, and sign them.

Documents are Values. JSON is at the edge

The engine works on Values: Null, Bool, Num (an exact BigDecimal), Str, Arr, Obj and SetV. It does not read the application's JSON.

Convert the documents at the edge of the application. rego4k-http4k-json does this for any http4k Json, so the application can keep its JSON library. http4k is a Kotlin library for HTTP servers and clients.

rego4k-http4k-json takes advantage of http4k, which already abstracts away the JSON implementations. Thus rego4k supports all the JSON libraries that http4k supports (Moshi, Kondor, Gson, ...), now and in the future. We do not write the same adapter layer again ourselves.

JSON text inside a policy. Rego also reads and writes JSON text: json.unmarshal, json.marshal, JWTs, http.send and AWS signatures. For this text, core has its own JsonReader and JsonWriter.

They copy Go's encoding/json:

We decided not to let an application put its own JSON library behind these builtins. Then the meaning of a policy would change with the configuration of the engine. For example, json.is_valid could accept JSON that OPA rejects, and Moshi would change 9007199254740993 to a Double.

In an authorization engine, that is a security problem. If an application needs different behaviour, it can replace one builtin by name. That change is explicit and visible.

YAML is optional

snakeyaml has a large CVE surface, so only rego4k-builtins-yaml uses it. YAML support is the yaml.* builtins.

Other code uses yaml.unmarshal if the engine has it:

An application whose policies have # METADATA blocks, but do not read them, can parse them as comments:

MetadataComments.kt
val rego = Rego(
    Builtins.Pure.stdlib(Re2Engine),
    parser = Parser(metadataBlocks = MetadataBlocks.COMMENTS),
)
MetadataComments.kt, lines 13 to 16, on GitHub

Then the engine needs no YAML. The option is explicit, because a policy that reads its annotations gives a different result without them: rego.metadata.rule() gives {}, and rego.metadata.chain() gives no annotations. OPA's parser has the same option (ProcessAnnotation).

The annotations have no other effect in rego4k:

http.send can run on an http4k HttpHandler

The http.send of Builtins.Impure.stdlib uses java.net.http. rego4k-builtins-http4k-send has a replacement that sends each request to an http4k HttpHandler that the application gives.

Add it after Builtins.Impure.stdlib, so that it replaces the standard builtin. It is impure, so a pure Rego rejects it:

HttpSendHandlers.kt
// a test, in memory
Rego(
    Builtins.Pure.stdlib(Re2Engine) +
        Builtins.httpSend(
            routes("/users/{id}" bind GET to { Response(OK).body("{}") }),
        ),
)
// production
Rego(
    Builtins.Pure.stdlib(Re2Engine) +
        Builtins.httpSend(ClientFilters.BearerAuth(token).then(JavaHttpClient())),
)
HttpSendHandlers.kt, lines 20 to 31, on GitHub

A test then runs a policy that calls http.send in the same process, with no network. A production engine gives an http4k client with its own filters, for example for authentication, time-outs and metrics.

The builtin gives the same results as OPA's http.send. The handler has the TLS configuration and the time-outs. See the README of rego4k-builtins-http4k-send.