Add, update, or remove OPA Rego built-in functions in rego-cpp. Use when: implementing a new builtin, replacing a placeholder with a real implementation, adding a new OPA builtin namespace, updating builtin declarations to match a new OPA version, removing deprecated builtins, or debugging builtin dispatch/registration. Covers the full lifecycle: declaration, implementation, dispatch registration, CMake wiring, and OPA conformance testing.
Add, update, or remove OPA Rego built-in functions in rego-cpp. Use when: implementing a new builtin, replacing a placeholder with a real implementation, adding a new OPA builtin namespace, updating builtin declarations to match a new OPA version, removing deprecated builtins, or debugging builtin dispatch/registration. Covers the full lifecycle: declaration, implementation, dispatch registration, CMake wiring, and OPA conformance testing.
argument-hint
Describe which builtin(s) to add, update, or remove.
rego-cpp Built-in Function Development
Add, update, and remove OPA Rego built-in functions in rego-cpp.
When to Use
Implementing a new builtin (replacing a placeholder or adding from scratch)
Adding a new OPA builtin namespace (new src/builtins/<namespace>.cc file)
Updating builtin declarations to track a new OPA version
Replacing placeholder stubs with real implementations
Removing deprecated builtins
Debugging builtin dispatch or registration issues
Architecture Overview
Built-in functions follow a three-layer architecture:
BuiltInsDef::lookup — hand-coded binary dispatch tree
src/builtins/<namespace>.cc
One file per OPA namespace (e.g., crypto.cc, jwt.cc)
src/CMakeLists.txt
SOURCES list — must include new .cc files
include/rego/rego.hh
Public API — BuiltIn, BuiltInDef, UnwrapOpt, helpers
The Binary Dispatch Tree
BuiltInsDef::lookup in src/builtins.cc uses a hand-coded binary search tree (generated by src/builtins/binary_tree.py) that routes the namespace prefix of a builtin name to the corresponding namespace function. When adding a new namespace, this tree must be regenerated or manually updated.
Special case: "io" prefix routes to builtins::jwt(name) for io.jwt.* builtins.
Procedure
Adding a New Builtin to an Existing Namespace
Read the existing namespace file (src/builtins/<namespace>.cc) to understand the patterns in use.
Write the implementation function:
Node my_func(const Nodes& args){
// Unwrap and validate arguments
Node x = unwrap_arg(args, UnwrapOpt(0).type(JSONString).func("namespace.my_func"));
if (x->type() == Error)
return x;
// Extract values
std::string val = get_string(x);
// Compute result
std::string result = do_something(val);
// Return wrapped resultreturn JSONString ^ result;
}
cd build && ./tests/rego_test -wf opa/v1/test/cases/testdata/v1/<testdir>
Adding a New Namespace
When adding an entirely new OPA namespace (new .cc file):
Create src/builtins/<namespace>.cc following the pattern of existing files. Include the anonymous namespace for internal functions and the rego::builtins namespace for the public dispatch function.
Declare the dispatch function in src/builtins/builtins.hh:
Add to the dispatch tree in src/builtins.cc — find the correct position in BuiltInsDef::lookup based on the namespace prefix string and add the routing branch. Alternatively, regenerate the tree using src/builtins/binary_tree.py.
Check the deprecated list in BuiltInsDef::is_deprecated in src/builtins.cc.
Add the builtin name to the deprecated vector if not already present.
Deprecated builtins return RegoTypeError when called, regardless of implementation.
Key Patterns
Argument Unwrapping
// Single type
Node x = unwrap_arg(args, UnwrapOpt(0).type(JSONString));
// Multiple accepted types
Node x = unwrap_arg(args, UnwrapOpt(0).types({JSONString, Int, Float}));
// With function name for error messages
Node x = unwrap_arg(args, UnwrapOpt(0).type(JSONString).func("crypto.sha256"));
// With custom error details
Node x = unwrap_arg(args, UnwrapOpt(0).type(JSONString)
.func("crypto.sha256").specify_number(true));
For compound results (arrays, objects, nested structures), use the rego API helpers declared in include/rego/rego.hh. These handle all Term/Scalar wrapping and cloning correctly, avoiding well-formedness errors:
// Booleans, strings, numbers, null — produce correctly-wrapped Scalar nodesreturnboolean(true); // same as True ^ "true" but self-documentingreturn rego::string("hello"); // note: qualify as rego::string to avoid std::stringreturnnumber(3.14);
returnnull();
// Arrays — items are auto-wrapped via Resolver::to_term()returnarray({boolean(true), rego::string("ok")});
returnarray({header_term, payload_term, rego::string(sig_hex)});
// Objects — built from object_item() nodesreturnobject({
object_item(rego::string("key"), rego::string("value")),
object_item(rego::string("count"), number(42.0))
});
// Nested: array of [bool, object, object]returnarray({boolean(false), object({}), object({})});
IMPORTANT: Never manually construct compound result nodes with NodeDef::create(Array), Term <<, Scalar <<, or push_back. These patterns produce nodes that violate well-formedness rules. Always use array(), object(), object_item(), boolean(), rego::string(), number(), and null() instead. These helpers call Resolver::to_term() internally, which handles all wrapping (Term, Scalar) and cloning correctly regardless of whether the input is a bare token, a Scalar, or an already-wrapped Term.
When a builtin needs to inspect or validate JSON data (e.g., JWT headers/payloads, JWK keys), always use the Trieste JSON parser (<trieste/json.h>) instead of manual string searching. Manual JSON parsing (e.g., json.find("\"field\""), character-by-character extraction) is brittle and will break on whitespace variations, escaped characters, nested structures, and field-name substrings.
Two JSON AST types exist — use the right one for the task:
AST type
Namespace
Produced by
Use for
JSON AST
json::Object, json::Array, json::String, ...
json::reader().synthetic(str).read()
Internal inspection: field lookup, type checking, claim validation
For internal inspection, parse into the JSON AST and use json::select with RFC 6901 JSON Pointer paths:
#include<trieste/json.h>// Parse raw JSON string into JSON AST
Node ast = parse_json(json_str); // json::reader().synthetic(str).read()// Field lookup — paths use RFC 6901 format with leading "/"auto alg = ::json::select_string(ast, {"/alg"}); // std::optional<Location>auto exp = ::json::select_number(ast, {"/exp"}); // std::optional<double>auto ok = ::json::select_boolean(ast, {"/active"}); // std::optional<bool>// Check field existence (select returns Error node if missing)
Node field = ::json::select(ast, {"/enc"});
if (field->type() != Error) { /* field exists */ }
// Check field type
Node aud = ::json::select(ast, {"/aud"});
if (aud->type() == ::json::Array) { /* it's an array */ }
// Nested pathsauto deep = ::json::select_string(ast, {"/foo/bar/baz"});
CRITICAL: The path argument is a Location initialized from a string literal with {"/field"} syntax. The leading / is required by RFC 6901. Using Location("field") without the / will fail silently.
For return values, use parse_json_to_term() (which runs json_to_rego) to produce Rego-typed nodes suitable for the evaluator. Parse into the JSON AST first for validation, then convert to Rego terms only at the end when building the return value.
For Rego Object nodes (e.g., constraint objects passed as builtin arguments), use try_get_string(node) and try_get_double(node) — these already handle Term/Scalar unwrapping. Do NOT navigate with node / Scalar before calling them.
Testing
OPA Conformance Tests
OPA test cases live in build/opa/v1/test/cases/testdata/v1/<testdir>/. Directory names match OPA builtin names with no separators (e.g., cryptohmacsha256, jwtdecodeverify).
# Run a specific builtin's testscd build && ./tests/rego_test -wf opa/v1/test/cases/testdata/v1/<testdir>
# List available test directoriesls build/opa/v1/test/cases/testdata/v1/ | grep <pattern>
# Run all OPA tests (slow)
ctest -R rego_test_opa
Custom Test Cases
Add YAML test cases to tests/regocpp.yaml or tests/bugs.yaml:
-note:mybuiltin/basicquery:data.test.p=xmodules:-|
package test
p := crypto.sha256("hello")
want_result:-x:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Error Message Matching
Error messages must match OPA exactly — conformance tests compare strings literally. When implementing error handling, check OPA's actual error output for the builtin.