Use rego4k in an existing application

This guide puts rego4k in a JVM service that calls OPA today, for example an OPA sidecar. The service then evaluates the same policies in its own process.

The policies, the input and the results stay the same: rego4k passes all 2538 cases of OPA's v1 conformance suite (OPA v1.23.0).

Each block of Kotlin on this page is a part of a complete program in site/examples, and the test LibraryGuideTest runs it.

Add the dependencies

Add the BOM, the core and the builtins:

build.gradle.kts
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")
    // only to convert the JSON of http4k
    implementation("dev.rego4k:rego4k-http4k-json")
    // your JSON library, for example Moshi or Kondor
    implementation("org.http4k:http4k-format-moshi")
}
BuildFilesTest.kt, lines 33 to 43, on GitHub

Each module is a module that you choose:

See Builtins: pure, provided and impure and Modules.

Compile the policy one time

This is the policy of the guides, authz.rego. An admin can do anything, and a viewer can read:

authz.rego
package authz

default allow := false

allow if "admin" in input.user.roles

allow if {
	input.method == "GET"
	"viewer" in input.user.roles
}

reasons contains "the user is not an admin" if not "admin" in input.user.roles
authz.rego, lines 2 to 13, on GitHub

Make one Rego and compile the modules when the application starts. A Rego is the engine: its builtins, its parser, its compiler and its evaluator. Rego.standard(Re2Engine) gives a new engine with the pure builtins of OPA's standard library.

Use the same compiled policy for all the requests. Do not compile it again for each request.

Authorization.kt
private val policy = Rego.standard(Re2Engine).compile(policies)
Authorization.kt, lines 22 to 22, on GitHub

policies is the Path of the directory of your policies. Each .rego file below it is a module, and the name of the module is its path, as in opa eval -d policies.

RegoFileName and RegoFile are two types, so a call cannot exchange the name and the source of a module by mistake.

For other builtins or parts, use Rego(...) with named arguments, for example Rego(Builtins.Pure.stdlib(Re2Engine) + Builtins.Provided.stdlib, clock = clock).

If your policies are an OPA bundle, read the bundle. Bundle is in rego4k-bundles-core:

BundleAuthorization.kt
private val rego = Rego.standard(Re2Engine)
// a directory or a .tar.gz file
private val bundle = Bundle.read(bundlePath)
private val policy = bundle.compile(rego)
// the data files of the bundle, as one document
val data = bundle.data(rego)

fun allowed(input: Value): Boolean = policy.allowed("data.authz.allow", input, data)
BundleAuthorization.kt, lines 13 to 20, on GitHub

Give data to each query, as the data parameter of allowed, eval or result.

Convert the input

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

Convert the input at the edge. With rego4k-http4k-json, any http4k Json can do it, for example Moshi or Kondor. parseValue reads JSON text, and toValue converts a JSON node:

Authorization.kt
// http4k-format-moshi
val withMoshi = Moshi.parseValue(requestBody)
// http4k-format-kondor-json
val withKondor = KondorJson().parseValue(requestBody)
Authorization.kt, lines 59 to 62, on GitHub

You can also make the values from Kotlin data. Value.of converts maps, lists, sets, strings, numbers, booleans and null. Value.of with pairs makes an object from its entries:

Authorization.kt
val bob = Value.of(
    "method" to "DELETE",
    "user" to Value.of("name" to "bob", "roles" to listOf("viewer")),
)
Authorization.kt, lines 40 to 43, on GitHub

Evaluate a decision

Authorization.kt
// true only if the value is true
val allowed = policy.allowed("data.authz.allow", input)
// any value, as Kotlin data
val reasons = policy.eval("data.authz.reasons", input)?.toKotlin()
Authorization.kt, lines 29 to 32, on GitHub

Do not count the solutions of query: as in OPA, a decision whose value is false still gives one solution.

To evaluate the same query on each request, prepare it once, for example in a property of the class that evaluates it:

Authorization.kt
// parses and compiles the query one time
private val allow = policy.prepare("data.authz.allow")

fun allowed(input: Value): Boolean = allow.allowed(input)
Authorization.kt, lines 49 to 52, on GitHub

Errors

A parse error, a compile error and an error of an evaluation are a RegoException, with the codes and the messages of OPA.

A builtin error makes the value undefined, as in OPA. To get the error, give strictBuiltinErrors = true to Prepared.result.

Errors.kt
try {
    return Rego.standard(Re2Engine)
        .compile(RegoFileName("broken.rego") to RegoFile(source))
} catch (e: RegoException) {
    // rego_parse_error: unexpected eof token
    log.error("${e.code}: ${e.message}")
    throw e
}
Errors.kt, lines 19 to 26, on GitHub

Keep the compiled policies in a cache

An application that compiles the same modules again, for example on each reload of a bundle, can give the engine a RegoCache.

Caches.kt
val rego = Rego.standard(
    Re2Engine,
    cache = RegoCache(maxBytes = 64L * 1024 * 1024, maxEntries = 100),
)
Caches.kt, lines 11 to 14, on GitHub

By default, a Rego keeps nothing (RegoCache.NONE).

Next steps