Home

Awesome

CI Coverage Status

Open Policy Agent (OPA) WebAssembly dotnet core SDK

This 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.

Key Features

NuGet Packages

OfficialPreview
OpaDotNet.WasmNuGetNuget
OpaDotNet.Extensions.AspNetCoreNuGetNuget
OpaDotNet.Compilation.CliNuGet-
OpaDotNet.Compilation.InteropNuGet-

Getting Started

Install nuget package

dotnet add package OpaDotNet.Wasm

Usage

To evaluate OPA policy you need to:

Load compiled policy

using using OpaDotNet.Wasm;

const string data = "{ \"world\": \"world\" }";

using var engine = OpaEvaluatorFactory.CreateFromWasm(
    File.OpenRead("policy.wasm")
    );

engine.SetDataFromRawJson(data);

Evaluate policy

IOpaEvaluator has several APIs for policy evaluation:

var policyResult = engine.EvaluatePredicate(inp);

Check result

if (policyResult.Result)
{
    // We've been authorized.
}
else
{
    // Can't do that.
}

Writing policy

See writing policy

Compiling policy

You have several options to compile rego policy into wasm module:

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);

3rd Party Libraries and Contributions