Why rego4k

OPA is the standard engine for Rego, and it is written in Go. A JVM application has these choices to use it:

rego4k is a third choice: a library that evaluates Rego in the same process, with the same results as OPA. An engine that we control, in a language and runtime that we know, also gives a Kotlin codebase these things.

A step-through debugger for policies

We want to see how a policy makes its decision: to step through the Rego, and to see which part of the input each step examines.

The debugger shows the part of the input that each step reads, and it steps back. It also shows the output document as the rules make it.

To show it, do these steps:

  1. Run ./gradlew :server-debugger:runExample. It opens the page in your browser, with an example policy: the rule allow reads the roles of the user, and the rule deny reads the price of each item.
  2. Press Ctrl+Enter (or click Debug) to start a replay of the query data.app.
  3. Press F11 a few times. The code view marks each step. At some role in input.user.roles, the Input panel highlights input.user.roles[0], and the Bindings panel shows role.
  4. Click the line number of item.price > 100 (line 12) to set a breakpoint, then press F8. The debugger stops for each item, and the Input panel highlights input.items[0].price, then input.items[1].price.
  5. Press F8 again. The Output panel shows deny as it grows: "item b costs too much".
  6. Click Step back. Each step evaluates the query again from the start, so the server keeps no state, and a step back is as cheap as a step forward.

The first start compiles the modules, so it can take a minute. After that, the page opens in about 3 s.

A small attack surface

The OPA 1.23.0 binary holds 84 Go modules (go version -m opa lists them), for example gRPC, Protocol Buffers, about 30 OpenTelemetry modules, ORAS and Prometheus, and the Go standard library. A CVE in any of them is a CVE alert in the image of the application.

For example, CVE-2022-41717 is in golang.org/x/net, and OPA v0.47.2 was a release only to update that module. OPA has CVEs of its own too, for example CVE-2025-46569 in its server and CVE-2024-8260 on Windows.

rego4k keeps its dependencies to a minimum, so that it causes few alerts:

The build locks its dependencies. A lock file (gradle.lockfile in each module) pins the version of each dependency, transitive dependencies included. Thus a build cannot use a new version of a dependency without a commit.

If a dependency has no lock state, the build fails. The lock files also pin the Gradle plugins of the build and the tools of the build, for example the Kotlin compiler and PIT, the mutation test tool for Java.

The AST in Kotlin

The parser and the compiler give typed Kotlin data, not text. An application can do any static analysis that it needs, for example to find the rules that read a part of the input, or to check a policy against the rules of a team. rego4k-server-lsp is a language server that is built on it.

Hackable, composable, pluggable

Each component of rego4k is an interface, even when it has only one implementation: Rego, the Parser, the Compiler, the TypeChecker, the Evaluator and the RegoCache, and so on. Rego gets its parts by constructor injection, so an application can replace or decorate any part and still compose a working system. A test runs this example:

ReplaceableParts.kt
val parser = Parser(Builtins.Pure.stdlib(Re2Engine))
val rego = Rego(
    builtins = Builtins.Pure.stdlib(Re2Engine),
    // a decorator of the default parser
    parser = object : Parser by parser {
        override fun parseModule(source: String, file: String) =
            logTime("parse") { parser.parseModule(source, file) }
    },
    cache = RegoCache(maxBytes = 64_000_000),
)
ReplaceableParts.kt, lines 17 to 26, on GitHub

rego4k also hides little. A declaration is private only if a use from outside is dangerous.

A part that can change in any release is marked @Rego4kVolatile. You can use it, but you must opt in (@OptIn(Rego4kVolatile::class)), so that you know that you depend on it.

rego4k is hackable. We want to provide you with a toolkit that allows you to solve problems we did not anticipate by recombining or replacing parts in novel ways. We try to stick to the properties of CUPID.

Tree shaking

Teams share Rego. A lib directory with the rules for roles, change windows and requests goes into the bundle of each service. The authz/allow decision of one service can use 10% of those rules, but the other 90% are in its bundle too.

A reader of the policy must find out which rules the decision can reach, and a review or an audit must read all of them.

Bundle.shake does that work. It follows the references from each entrypoint, and it makes a bundle with only the rules and the data that the entrypoints can reach:

roles.rego
# The shaken bundle keeps this file without `can_audit`:
# lib/roles.rego
package lib.roles

# reachable: authz.allow calls it
is_admin(user) if user in data.roles.admins
# not reachable
can_audit(user) if user in data.roles.auditors
roles.rego, lines 2 to 9, on GitHub
Deploy.kt
val shaken = bundle.shake(rego, "authz/allow")
Deploy.kt, lines 27 to 27, on GitHub

The shaken bundle also keeps its hash stable. Many systems decide from the hash of a bundle that a policy changed:

If each bundle holds the whole lib directory, a change to any shared rule changes the hash of each bundle. This occurs even when no entrypoint of the bundle reads that rule.

A shaken bundle keeps only the source text of the reachable rules. Thus a change to an unreachable rule does not change its bytes or its hash, and the hash changes only when the behaviour of an entrypoint can change. The .manifest stays as it is, so a change to it still changes the hash.

By default, the shaken bundle has no wasm modules, because rego4k cannot compile Rego to WebAssembly. An application that needs them gives a WasmBuilding, for example Opa.cli(), and OPA builds new wasm modules from the shaken Rego. See rego4k-opa-core.

Bundle.shake also lists the builtins that the kept rules call. Give an engine only those builtins, and the policy cannot call a builtin that its entrypoints do not use, for example http.send. See rego4k-bundles-core.

To see what tree shaking does before you deploy, Bundle.shakeDryRun lists the lines of each file that the shaken bundle keeps, deletes and adds. The module rego4k-server-shaking shows it as JSON and as a page, with each deleted line struck through. The demo opens that page from the page of each policy.

A choice of deterministic policies

An application can choose to allow only policies whose results are deterministic and can be reproduced. Each builtin has one of three kinds:

Kind Its result depends on Examples Can a query give the same result again?
Builtin.Pure its arguments only count, sprintf, regex.match Yes, always.
Builtin.Provided its arguments, and a value that the runtime gives to the query time.now_ns, time.date with a zone, opa.runtime Yes, if the query gets the same value again. rego4k records each provided value that the query reads, for example the time and the version of the time zone data, so that it can give it again.
Builtin.Impure something that nobody can give again rand.intn, http.send, uuid.rfc4122 No. A random value comes from the algorithm of this version, and a server can answer differently tomorrow.

A pure Rego accepts pure and provided builtins, and rejects each impure builtin. See A query result can be reproduced.

Signed decisions

rego4k-signing-signer signs the output of a query with the hashes of the policy, the input and the data. The result is an in-toto statement. cosign, the signing tool of the Sigstore project, can verify it.

A verifier can evaluate the query again with the same provided values.

rego4k-server-signing adds to the server, like OPA's, a route that signs each decision for the principal of the caller. Another system verifies it with only the certificate of an authority.

The caller does not know the provided values before the query, so each signed decision gives them, and the signature covers them. The plain Data API of the server gives them with provided=true.

http.send in memory

A policy that calls http.send is hard to test with OPA. Each test needs a server, a free port and the network, so the tests are slow and can fail for reasons that have nothing to do with the policy.

rego4k-builtins-http4k-send sends each request to an http4k HttpHandler, not to the network. In a test, the handler is a function in memory, so a test of a policy that calls http.send is as fast as any other unit test and needs nothing to be running:

HttpSendInMemory.kt
val staffDirectory: HttpHandler = routes(
    "/staff/{id}" bind GET to {
        Response(OK)
            .header("Content-Type", "application/json")
            .body("""{"manager": "bob"}""")
    },
)
val rego = Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.httpSend(staffDirectory))
HttpSendInMemory.kt, lines 22 to 29, on GitHub

The same policy in production gets an HTTP client, with its own filters for timeouts, retries and authentication.

Deterministic bundles

A bundle written by rego4k always has the same bytes. Bundle.hash can leave out the revision, so that a deployment changes only when the behaviour can change.

Rego tests in the build of the application

Teams write Rego tests for their policies: rules whose names start with test_. opa test runs them. rego4k runs the same tests without the opa binary, with the same outcomes and the same text (see rego4k-testing-core).

With rego4k-testing-junit, each Rego test is a JUnit test, so Gradle and the IDE show it next to the Kotlin tests:

PolicyTests.kt
@TestFactory
fun policies() = RegoTests.junit(
    Rego.standard(Re2Engine),
    File("src/main/kotlin/rego4k/examples/policies"),
)
PolicyTests.kt, lines 24 to 28, on GitHub

just test-rego <path> runs the tests on the command line, with the text and the exit codes of opa test. It runs rego4k test, the test command of rego4k's command line.

A test compares the two on 26 directories of policies. The bundles default, expenses, orders and platform of the demo have tests.

A command line like opa

rego4k is the command line of opa with rego4k in place of OPA: eval, check, fmt, parse, test and build, with OPA's flags, output and exit codes. It is one jar, so it runs on each platform that has a JVM, with no Go binary. Scripts, CI steps and pre-commit hooks that call opa fmt or opa check can call it with no other change.

sh
just cli
rego4k eval -d policies -i input.json -f pretty data.authz.allow

A test runs the same command lines through opa and rego4k, and compares the output and the exit codes. Thus a capability that rego4k does not have shows as a failed command. See modules/cli and modules/cli/opa.

The jar also has the commands of rego4k's other areas:

sh
rego4k run --server -b bundle.tar.gz --with-debugger --with-shaking      # the decision server, as `opa run --server`
rego4k shake -e authz/allow --wasm -o shaken.tar.gz bundle.tar.gz         # tree shaking, then `opa build -t wasm`
rego4k sign-decision -b bundle.tar.gz -i input.json --signing-key leaf.key --signing-algorithm ES256 authz/allow
rego4k verify-decision --trusted-authority root.pem --trusted-algorithm ES256 decision.json

See modules/cli/server, modules/cli/shaking and modules/cli/decision-signing.

Partial evaluation, for data filtering

Rego.Policy.partial evaluates a query with unknown documents, as opa eval --partial does. The result is the conditions on the unknown documents that make the query true: the residual queries, and the support modules that they refer to. An application changes them into a filter of a database query.

This is the data-filtering example of OPA's documentation, with input.document unknown:

example.rego
package example

allow if {
	input.method == "GET"
	input.document.owner == input.user
}

allow if {
	input.method == "GET"
	input.document.public == true
}
example.rego, lines 2 to 12, on GitHub
PartialEvaluation.kt
val result = policy.partial(
    "data.example.allow == true",
    input = Value.of("user" to "alice", "method" to "GET"),
    unknowns = listOf("input.document"),
)
val queries = result.queriesJson()
val support = result.supportJson()
PartialEvaluation.kt, lines 21 to 27, on GitHub

The two residual queries are "alice" = input.document.owner and input.document.public = true, as OPA's AST JSON. They need no support modules.

Toolchain.embedded implements the capability PartialEvaluation with it. The partial evaluator is a second evaluator, a port of OPA's, so that the residual queries are OPA's (see Partial evaluation in the divergences).

OpaPartialEvaluationTest compares the JSON with opa eval --partial on its own policies and on each case of OPA's conformance suite, with input unknown. In 2168 of the 2193 cases, the JSON is the same.

No limits from the stack

A long body, a deep rule chain or a deep document does not overflow the stack, and rego4k has no limit on the depth of JSON or YAML. See Divergences from OPA.