Kotlin-native Rego as a hackable toolkit

A JVM application can run Rego via a sidecar, a remote server, or wasm in GraalWasm.

rego4k is a Kotlin library that evaluates Rego in your process, with the same results as OPA.

It also adds helpful new capabilities beyond what is possible with OPA.

What changes when the engine is JVM-native?

A step-through debugger you can host in your JVM/Datastar app

When a policy gives a decision that you did not expect, you want to see which part of the input each step read.

  • Regal, the linter and language server for Rego, steps through a policy in your editor.
  • rego4k-server-debugger steps through it in the browser, and it can run inside your own application, behind your login. It highlights the part of the input that each step reads.

The debugger is a set of http4k routes and kotlinx.html components. Datastar, a small JavaScript library for pages that the server renders, updates the page in the browser.

The routes keep no state. The state of a debug session is in the Datastar signals of the page, and each response patches the signals and the page. Give your own DebuggerComponents, and the same routes drive a different UI. See The routes and the signals.

Mount DebuggerModule below a path of your own application, in your navigation, or run it as a server of its own with rego4k run --server --with-debugger. DebuggerComponents lets you redraw any part of the page.

Each step evaluates the query again from the start, so a step back costs the same as a step forward. Open the debugger at demo.rego4k.dev.

Replace it: draw each part of the page with your own DebuggerComponents, and list your own bundles with a BundleCatalog.

The debugger of the demo paused at a breakpoint on line 12 of approval.rego, not money.within_limit(...), for an order of 2500 over the limit. The code view marks the line, and the Input panel marks the part of the input that the line reads.The debugger of the demo paused at a breakpoint on line 12 of approval.rego, not money.within_limit(...), for an order of 2500 over the limit. The code view marks the line, and the Input panel marks the part of the input that the line reads.

The core of the engine has two dependencies that you can read in an hour

A CVE in any of the 84 Go modules of OPA's binary is an alert in your image. OPA v0.47.2 was a release only to update golang.org/x/net for CVE-2022-41717.

rego4k-core depends only on parser4k and tuples4k, beside the Kotlin standard library. A module that needs an external library, such as YAML or RE2, is a module that you choose to add.

Replace it: give Rego only the Builtins that you need. The default engine has no builtins.

rego4k-core
about 1070 linesof Kotlin in parser4k and tuples4k, its only dependencies.
opa 1.23.0
84 Go modulesin the binary, for example gRPC, Protocol Buffers, about 30 OpenTelemetry modules and Prometheus.

The parser gives you the policy as typed Kotlin data

With OPA, a check of your policies against the rules of your team starts from the JSON of opa parse. The parser and the compiler of rego4k produce Kotlin data classes.

Write the static analysis that your team needs, for example to find the rules that read a part of the input. rego4k-server-lsp, a language server for Rego, is built on the same AST.

Replace it: Parser and Compiler are interfaces. Give your own to Rego as its parser and its compiler.

policy.regoline 6
some role in input.user.roles
Ast.kt, lines 13 to 13, on GitHub
rego4k.astthe parsed expression, shortened
Expr(
    SomeIn(
        key = null,
        value = Var("role"),
        collection = Ref(
            head = Var("input"),
            path = listOf(Scalar(Str("user")), Scalar(Str("roles"))),
        ),
    ),
)
Ast.kt, lines 20 to 29, on GitHub

Tree shaking: bundle only the rules that a decision can reach

Teams share a lib directory of Rego, and each service bundles all of it. A change to any shared rule then changes the hash of each bundle.

Bundle.shake follows the references from each entrypoint and keeps only the rules and the data that they reach. The hash of the bundle then changes only when an entrypoint can behave differently. The shake also lists the builtins that the kept rules call.

Deploy.ktrego4k-bundles-core
val shaken = bundle.shake(rego, "authz/allow")
Deploy.kt, lines 27 to 27, on GitHub

Before

authz/policy.regothe service's policy
package authz

import data.lib.roles

allow if roles.is_admin(input.user)

audit if roles.can_audit(input.user)
policy.rego, lines 2 to 8, on GitHub
lib/roles.regoshared by each service
package lib.roles

is_admin(user) if user in data.roles.admins

can_audit(user) if user in data.roles.auditors
roles.rego, lines 2 to 6, on GitHub

After the shake for authz/allow

authz/policy.regoaudit is gone
package authz

import data.lib.roles

allow if roles.is_admin(input.user)
policy.rego, lines 2 to 6, on GitHub
lib/roles.regocan_audit is gone
package lib.roles

is_admin(user) if user in data.roles.admins
roles.rego, lines 2 to 4, on GitHub

Restrict the engine to builtins that you can reproduce

You can restrict an engine to the builtins whose results can be reproduced. OPA can limit a policy to a list of builtins by name, in a capabilities file.

In rego4k, each builtin is pure, provided or impure, and the kind is part of its type. Thus a builtin that you write, or one from a third-party library, declares its kind, and the restriction applies to it too.

  • Impure: Rego(builtins, pure = true) refuses an impure builtin, such as http.send or rand.intn. The engine does not compile a policy that calls one.
  • Provided: a provided builtin, such as time.now_ns, reads a value that the runtime gives. The query records each such value.

So a year after a decision, you can evaluate the query again with the same values, and get the same result.

Replace it: give Rego its clock, a java.time.InstantSource. A fixed clock gives a test the same time on each run.

KindIts result depends onExamples
Builtin.Pureits arguments onlycount, sprintf, regex.match
Builtin.Providedits arguments, and a value that the runtime gives and the query recordstime.now_ns, time.date with a zone, opa.runtime
Builtin.Impuresomething that nobody can give againrand.intn, http.send, uuid.rfc4122
Audit.ktrego4k-builtins-stdlib-provided
// rejects each impure builtin when the builtins are registered
Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.Provided.stdlib, pure = true)
Audit.kt, lines 13 to 14, on GitHub

Signed in-toto statements for SLSA, for each decision

When another team asks what your policy decided, the answer is a log line, and they must trust the system that wrote it.

rego4k-signing-signer signs each decision as an in-toto Statement v1 in a DSSE envelope. This is the attestation format of SLSA, which supply-chain tools already read.

  • The subject is the SHA-256 of the input.
  • The predicate type is https://rego4k.dev/decision/v1.
  • The predicate holds the entrypoint, the output, the time, the hashes of the policy bundle and the data, the provided values that the query read, and the principal that sent the input.

cosign, the signing tool of the Sigstore project, verifies it with verify-blob-attestation --type https://rego4k.dev/decision/v1. rego4k-signing-verifier verifies it in a JVM with only the certificate of your authority.

A verifier can evaluate the query again with the same provided values and get the same output. rego4k-server-signing adds a route to the server that signs each decision for the principal of the caller.

  1. The query gives its output and the provided values that it read.
  2. The signer adds the hashes of the policy, the input and the data.
  3. The in-toto statement goes into a DSSE envelope, signed with your key, with its certificate chain in x5c.
  4. A receiver verifies it with only the certificate of the authority, or with cosign.

Hackable, composable, pluggable

When an engine does almost what you need, you work around it from the outside.

rego4k is a set of parts that you compose. The engine, the builtins, the bundles, the servers and the debugger are separate Maven modules, so you add only the ones that you need. See Modules.

Inside the engine, each component is an interface, and Rego gets its parts by constructor injection. Wrap one part, and the engine still works.

A part that can change in any release has @Rego4kVolatile, so you opt in before you depend on it.

ReplaceableParts.ktrego4k-core
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

http4k + Datastar integrations

The servers and the debugger of rego4k are http4k routes in your own application, so your policies need no second process with its own port and its own authentication.

  • Pick the routes. Each part of the decision server is an http4k ServerModule in its own Maven module: OPA's REST API, signed decisions, the debugger, tree shaking and the API docs. Mount puts one below a path of your application, behind your own filters.
  • Bridge to your server. http4k's bridge modules hand requests from Spring, Ktor, Micronaut, Helidon, Vert.x, Ratpack, Jakarta or a servlet container to the modules.
  • Reskin with Datastar. The server renders the pages with kotlinx.html, and Datastar patches them in the browser. PageFrame, DebuggerComponents and CSS variables change the look.
  • JSON with Moshi, Kondor or Gson. rego4k-http4k-json converts any http4k Json to the values of rego4k.
  • Test http.send in memory. http.send runs on an http4k HttpHandler, so a unit test gives the policy a handler in memory.
  • Few dependencies. http4k-core needs only the Kotlin standard library, result4k and values4k. Datastar is one script of 14 KB when compressed.

Why we chose http4k and Datastar

Replace it: a ServerModule is a name, contract routes and a filter. Mount your own next to the modules of rego4k.

AdminApplication.ktrego4k-server-core, rego4k-server-debugger
val opa = DecisionServer(Filter.NoOp, listOf(OpaApi.module(bundles)))
// your navigation around it
val debugger = Debugger(rego, catalog = myCatalog, frame = adminFrame)
val application = adminLogin.then(
    routes(
        "/admin" bind GET to adminHome,
        Mount("/admin/policies/opa", opa).route,
        Mount("/admin/policies/debug", debugger).route,
    ),
)
AdminApplication.kt, lines 53 to 62, on GitHub

What we measured against OPA 1.23.0

To check a decision yourself, step through a policy in your browser at demo.rego4k.dev.

Start from the system that you run today

Nothing is on Maven Central yet. The first release will put each module there in the group dev.rego4k, with the BOM rego4k-bom, which gives each module the same version.

Until then, run ./gradlew publishToMavenLocal in a clone of the repository, and add mavenLocal() to the repositories of your build.

  1. Use the library in an existing application

    If your service is currently calling an OPA sidecar, evaluate the same policies in its process. Use rego4k-http4k-json to convert JSON from a request, using any popular JSON library.

    Read the guide for the library
  2. Build a custom decision server

    If other services call OPA's REST API, serve the same API from your own http4k application. Then add what you need, such as signed decisions, or the debugger behind your own login.

    Read the guide for the server
  3. Test your Rego with JUnit

    If opa test runs apart from your build, run it in the build. Each Rego test becomes a JUnit test, so Gradle and the IDE show it next to your Kotlin tests.

    Read the guide for tests
  4. Try the debugger

    To see a policy run first, step through the policies of the demo bundles in your browser.

    Open demo.rego4k.dev
build.gradle.ktsthe library path
dependencies {
    implementation(platform("dev.rego4k:rego4k-bom:$rego4kVersion"))
    implementation("dev.rego4k:rego4k-core")
    implementation("dev.rego4k:rego4k-builtins-stdlib-pure")
    // the regex engine of OPA
    implementation("dev.rego4k:rego4k-builtins-re2")
    testImplementation("dev.rego4k:rego4k-testing-junit")
}
BuildFilesTest.kt, lines 16 to 23, on GitHub
Authz.ktrego4k-core, rego4k-http4k-json
val policy = Rego.standard(Re2Engine)
    .compile(RegoFileName("authz.rego") to RegoFile(source))

// rego4k-http4k-json
val input = Moshi.parseValue(requestBody)
val allowed = policy.allowed("data.authz.allow", input)
Authz.kt, lines 15 to 20, on GitHub