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:
rego4k-builtins-stdlib-pureholds the pure builtins of OPA's standard library.- Add
rego4k-http4k-jsononly if you want to convert the JSON of an http4kJsonto the values of rego4k. http4k is a Kotlin library for HTTP.
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 GitHubEach module is a module that you choose:
- To read the time, add
rego4k-builtins-stdlib-provided. - For
http.send, addrego4k-builtins-stdlib-impure. - For the
yaml.*builtins and# METADATAblocks, addrego4k-builtins-yaml.
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:
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.rolesauthz.rego, lines 2 to 13, on GitHubMake 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.
private val policy = Rego.standard(Re2Engine).compile(policies)Authorization.kt, lines 22 to 22, on GitHubpolicies 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.
- To compile one file, give its path.
- To compile text, give the name and the text of each module:
rego.compile(RegoFileName("authz.rego") to RegoFile(source)).
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:
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 GitHubGive 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:
// http4k-format-moshi
val withMoshi = Moshi.parseValue(requestBody)
// http4k-format-kondor-json
val withKondor = KondorJson().parseValue(requestBody)Authorization.kt, lines 59 to 62, on GitHubYou 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:
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 GitHubEvaluate a decision
allowedis true only when the value of the query istrue, asResultSet.Allowed()is in OPA's Go API.- Use
evalfor any other value.evalgives null when the value is undefined. toKotlingives the Kotlin data of a value: a set of Rego is aSet, and a number is an exactBigDecimal.
// 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 GitHubDo 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:
// 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 GitHubErrors
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.
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 GitHubKeep 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.
- The cache keys a policy by a SHA-256 hash of its modules, its parser and its compiler.
- When the cache is over its limits, it removes the policy that was used least recently.
val rego = Rego.standard(
Re2Engine,
cache = RegoCache(maxBytes = 64L * 1024 * 1024, maxEntries = 100),
)Caches.kt, lines 11 to 14, on GitHubBy default, a Rego keeps nothing (RegoCache.NONE).
Next steps
- Test your Rego with JUnit: run the Rego tests of the policies in the build of the application.
- Build a decision server: if other services call your policies over HTTP.
- Hackable, composable, pluggable: replace or decorate a part of the engine.
- The README of
rego4k-coredescribes all of the API of the engine.