Open Policy Agent (OPA) WebAssembly dotnet core SDK
$ dotnet add package OpaDotNet.WasmThis is SDK for using WebAssembly (wasm) compiled Open Policy Agent policies with dotnet core.
Initial implementation was based on Open Policy Agent WebAssemby NPM Module
For more information check out the guide.
dotnet add package OpaDotNet.Wasm
To evaluate OPA policy you need to:
using using OpaDotNet.Wasm;
const string data = "{ \"world\": \"world\" }";
using var engine = OpaEvaluatorFactory.CreateFromWasm(
File.OpenRead("policy.wasm")
);
engine.SetDataFromRawJson(data);
IOpaEvaluator has several APIs for policy evaluation:
EvaluatePredicate - Evaluates named policy with specified input. Response interpreted as simple true/false
result.Evaluate - Evaluates named policy with specified input.EvaluateRaw - Evaluates named policy with specified raw JSON input.var policyResult = engine.EvaluatePredicate(inp);
if (policyResult.Result)
{
// We've been authorized.
}
else
{
// Can't do that.
}
See writing policy
You have several options to compile rego policy into wasm module:
package example
default hello = false
hello if {
x := input.message
x == data.world
}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.regoWhich 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.
You can use SDK to do compilation for you. For more information see OpaDotNet.Compilation.
dotnet add package OpaDotNet.Compilation.Cliusing 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);dotnet add package OpaDotNet.Compilation.Interopusing 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);