Why rego4k
OPA is the standard engine for Rego, and it is written in Go. A JVM application has these choices to use it:
- Call an OPA server (a sidecar or a service). This adds a process, a network call and a deployment.
- Run OPA's WebAssembly build in a WebAssembly runtime. This needs a runtime, and the WebAssembly build does not include all builtins. The application must supply many of them itself.
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.
- Regal, the linter and language server for Rego, steps through a policy in your editor.
rego4k-server-debuggersteps through it in the browser, and it can run inside your own application, behind your login.
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:
- Run
./gradlew :server-debugger:runExample. It opens the page in your browser, with an example policy: the ruleallowreads the roles of the user, and the ruledenyreads the price of each item. - Press Ctrl+Enter (or click Debug) to start a replay of the query
data.app. - Press F11 a few times. The code view marks each step. At
some role in input.user.roles, the Input panel highlightsinput.user.roles[0], and the Bindings panel showsrole. - 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 highlightsinput.items[0].price, theninput.items[1].price. - Press F8 again. The Output panel shows
denyas it grows:"item b costs too much". - 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:
rego4k-coredepends only on parser4k (with itstuples4k) and the Kotlin standard library. parser4k and tuples4k are small and simple: together about 1070 lines of Kotlin in 24 files (about 800 lines of code; most of tuples4k is generated tuple types), with no other dependencies. You can read all of it in an hour.- OPA's standard library (
rego4k-builtins-stdlib-pure,rego4k-builtins-stdlib-providedandrego4k-builtins-stdlib-impure), bundles, bundle signing and signed decisions add no external dependency. They use the JDK, for example for the cryptography. - Each module that needs an external dependency is a module that you choose:
-
rego4k-builtins-yaml: snakeyaml-engine, a YAML 1.2 parser. OPA'syaml.*builtins, YAML data files in bundles and# METADATAblocks need it, and the JDK has no YAML parser. -
rego4k-builtins-re2: re2j, Google's port of the RE2 regex engine to Java. OPA uses Go's RE2, so re2j gives OPA's regex syntax and results, and a time that grows linearly with the input.JavaRegexEngineusesjava.util.regex, which differs from RE2 (see Regex withjava.util.regex). -
rego4k-http4k-json,rego4k-builtins-http4k-send,rego4k-server-policiesandrego4k-server-debugger: http4k, an HTTP toolkit for Kotlin.rego4k-http4k-jsonconverts the JSON of http4k to values.rego4k-builtins-http4k-sendsendshttp.sendto anHttpHandler.- The decision server and the debugger are web servers.
We chose http4k because it has few dependencies and a very good record of CVEs.
-
rego4k-server-policiesandrego4k-server-debuggeralso usehttp4k-api-openapi(the typed routes and their OpenAPI description) andhttp4k-format-kondor-json(the JSON of that description). They bring only small modules of http4k and Kondor, a small JSON library for Kotlin with no reflection.Kondor depends only on the Kotlin standard library. We did not use Jackson, which has many modules and a long record of CVEs. The Rego documents in the bodies of the server stay values, with the JSON of core.
-
rego4k-server-debuggeralso useshttp4k-web-datastar(the events of Datastar, a small JavaScript library for pages that the server renders), which bringsvalues4k. The debugger renders its HTML with kotlinx.html, which depends only on the Kotlin standard library. It serves the Datastar client (one JavaScript file, MIT licence) from its own module, and it has no other JavaScript. -
rego4k-server-docsshows the OpenAPI descriptions of the server as an HTML page, with kotlinx.html and no JavaScript. We did not use Swagger UI or Redoc: the browser loads them from a CDN, or http4k serves them from a webjar of more than 1 MB of JavaScript. -
rego4k-server-lsp: lsp4j, the Eclipse implementation of the Language Server Protocol for Java. It reads and writes the JSON-RPC messages between the editor and the language server, so thatrego4k-server-lspholds only the Rego part.
-
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:
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 GitHubrego4k 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:
# 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.auditorsroles.rego, lines 2 to 9, on GitHubval shaken = bundle.shake(rego, "authz/allow")Deploy.kt, lines 27 to 27, on GitHubThe shaken bundle also keeps its hash stable. Many systems decide from the hash of a bundle that a policy changed:
- to start a deployment;
- to clear a cache of decisions;
- to record which policy made a signed decision.
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:
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 GitHubThe 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:
@TestFactory
fun policies() = RegoTests.junit(
Rego.standard(Re2Engine),
File("src/main/kotlin/rego4k/examples/policies"),
)PolicyTests.kt, lines 24 to 28, on GitHubjust 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.
just cli
rego4k eval -d policies -i input.json -f pretty data.authz.allowA 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:
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.jsonSee 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:
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 GitHubval 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 GitHubThe 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.