Getting Started
Install nuget package
dotnet add package OpaDotNet.Wasm
Usage
To evaluate OPA policy you need to:
Add usings
using OpaDotNet.Wasm;
Load compiled policy
const string data = "{ \"world\": \"world\" }";
using var engine = OpaEvaluatorFactory.CreateFromWasm(
File.OpenRead("data/policy.wasm")
);
engine.SetDataFromRawJson(data);
Evaluate policy
IOpaEvaluator
has several APIs for policy evaluation:
EvaluatePredicate
- Evaluates named policy with specified input. Response interpreted as simpletrue
/false
result.Evaluate
- Evaluates named policy with specified input.EvaluateRaw
- Evaluates named policy with specified raw JSON input.
var input = new { message = "world" };
var policyResult = engine.EvaluatePredicate(input);
Check the result
if (policyResult.Result)
{
// We've been authorized.
}
else
{
// Can't do that.
}
More samples here
Writing policy
See writing policy
Compiling policy
You have several options to compile rego policy into wasm module:
Consider example.rego
file with the following policy:
package example
default hello = false
hello {
x := input.message
x == data.world
}
Manually
Either use the Compile REST API or opa build CLI tool.
For example, with OPA v0.20.5+:
opa build -t wasm -e example/hello example.rego
Which is compiling the example.rego
policy file.
The result will be an OPA bundle with the policy.wasm
binary included. See samples for a more comprehensive example.
See opa build --help
for more details.
With OpaDotNet.Compilation
You can use SDK to do compilation for you. For more information see OpaDotNet.Compilation.
OpaDotNet.Compilation.Cli
Important
You will need opa
cli tool to be in your PATH or provide full path in RegoCliCompilerOptions
.
dotnet add package OpaDotNet.Compilation.Cli
using OpaDotNet.Wasm;
using OpaDotNet.Compilation.Cli;
var compiler = new RegoCliCompiler();
var policyStream = await compiler.CompileFile("example.rego", new[] { "example/hello" });
// Use compiled policy.
using var engine = OpaEvaluatorFactory.CreateFromBundle(policyStream);
OpaDotNet.Compilation.Interop
dotnet add package OpaDotNet.Compilation.Interop
using OpaDotNet.Wasm;
using OpaDotNet.Compilation.Interop;
var compiler = new RegoInteropCompiler();
var policyStream = await compiler.CompileFile("example.rego", new[] { "example/hello" });
// Use compiled policy.
using var engine = OpaEvaluatorFactory.CreateFromBundle(policyStream);