Tiny, zero-allocation authorization engine for proxy-wasm and the edge. ~75 KB. No GC. No deps.
What it is: an authorization engine that fits in a proxy-wasm filter, so you can enforce policy at the edge without putting a 40 MB sidecar next to every proxy.
Why it exists: the usual way to run policy in Envoy is to call out to OPA -- a 40 MB binary and ~23 MB resident next to every proxy, answering in ~140 us over the loopback -- or to compile each policy to its own WASM module with opa build -t wasm and load that into the VM. zopa is one ~75 KB module that serves every policy, allocates from an arena it resets after every request, and answers in under a microsecond on simple rules. You give up the Rego language -- zopa runs a compiled Rego-shaped AST, not source -- and keep the decisions. See Numbers for where that trade does and does not pay off; OPA's WASM build is the closer competitor than its size suggests.
Hosts hand it a request input and a policy AST, both as JSON; zopa returns allow, deny, or error. It runs as a proxy-wasm filter in Envoy or any other proxy-wasm 0.2.1 host, and the same binary works as a plain WebAssembly.Module for hosts that just want to call evaluate(input, ast).
Status: alpha. The AST covers a subset of Rego -- 39 of the 54 constructs probed by zig build test-coverage, with the gaps named rather than described as "useful" (see Rego coverage). CI runs the suite under three wasm hosts (Node, wasmtime, and a real Envoy). Export names, AST schema, and callback semantics will change before 1.0.
Grab the module and make one decision, in about thirty seconds:
# from a release (cosign-signed, with SLSA provenance)
curl -fsSLO https://github.com/dyokto/zopa/releases/download/v0.8.0/zopa-v0.8.0.wasm
mv zopa-v0.8.0.wasm zopa.wasm
# or from the container image, rebuilt on every push to main
docker create --name zopa ghcr.io/dyokto/zopa:edge && \
docker cp zopa:/zopa.wasm . && docker rm zopa// decide.mjs -- node decide.mjs
import { readFileSync } from 'node:fs';
const { instance } = await WebAssembly.instantiate(
readFileSync('zopa.wasm'),
{ env: {
proxy_log: () => 0,
proxy_get_buffer_bytes: () => 1,
proxy_get_header_map_pairs: () => 1,
proxy_get_header_map_value: () => 1,
proxy_send_local_response: () => 0,
}},
);
const { malloc, free, evaluate, memory } = instance.exports;
const enc = new TextEncoder();
function write(obj) {
const bytes = enc.encode(JSON.stringify(obj));
const ptr = malloc(bytes.length);
new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
return [ptr, bytes.length];
}
const [ip, il] = write({ user: { role: 'admin' } });
const [ap, al] = write({
type: 'eq',
left: { type: 'ref', path: ['input', 'user', 'role'] },
right: { type: 'value', value: 'admin' },
});
console.log(evaluate(ip, il, ap, al)); // 1 = allow, 0 = deny, -1 = error
free(ip); free(ap);Or build it yourself -- one command, no dependencies to resolve:
zig build --release=small # -> zig-out/bin/zopa.wasm, ~75 KBRelease build against the two things zopa is meant to replace: OPA compiled to WASM and loaded in-process, and OPA run as a sidecar over loopback HTTP. zig build bench, Node host, 10k iterations after 1k warm-up. No engine is timed until all of them have returned the same decision for the fixture, so each row is a comparison rather than several unrelated measurements.
zopa appears twice, because the two generic-ABI shapes cost very different amounts. evaluate(input, ast) is handed the policy on every call and re-parses it; policy_compile + evaluate_compiled(handle, input) builds it once and keeps it, which is what the proxy-wasm path has always done internally.
Per-decision cost, microseconds:
| Policy | zopa (evaluate) | zopa (compiled) | OPA (wasm) | Cedar (native) | Cedar (wasm) | OPA (sidecar) |
|---|---|---|---|---|---|---|
literal allow = true |
0.34 | 0.09 | 0.87 | 2.84 | 11.8 | 131 |
input.method == "GET" |
1.02 | 0.21 | 1.01 | 5.45 | 14.8 | 135 |
| default-deny RBAC: path prefix + role + perms | 6.11 | 1.43 | 2.33 | 33.7 | 52.5 | 147 |
| zopa | OPA (wasm) | OPA (sidecar) | |
|---|---|---|---|
| deployed artifact | 75 KB, all policies | 131 KB per policy | — |
| memory after warm-up | 1.3-1.6 MB | 128 KB | 23 MB |
| cold start | 0.4-1.3 ms | 0.5-1.5 ms | 57-60 ms |
What those say:
- Compile the policy once if you serve traffic. The gap between the two zopa columns is the AST parse and nothing else: 4.7 µs of the 6.11 on the RBAC row.
evaluateis for tests, one-shot callers, and hosts that genuinely get a different policy every time. - Held that way, zopa is faster than OPA's wasm build on every fixture, and 1.6x faster on the realistic one. Through
evaluateit was 2.6x slower on that same row -- the parse was the whole difference. - Against a sidecar, either in-process engine wins by ~100x. That is the claim zopa is built on. It is also the least interesting row: it compares a TCP round trip to a function call.
- Neither Cedar column is a verdict on Cedar's evaluator. The WASM binding costs it 3-4x over a native
cedar-policyembedding, and what remains after that is request conversion, not evaluation: Cedar answers the RBAC fixture in 2.00 µs once it holds the request -- 1.4xzopa (compiled). The rest isContext::from_json_valueturning a JSON document into Cedar's typed values. Cedar expects a request assembled from typed application state; zopa and OPA expect one that arrives as JSON on the wire. Both columns are inbench/README.mdwith the split shown. - zopa holds more WASM memory than OPA's module does -- ~1.4 MB against 128 KB. The arena is reset with
.retain_capacity, trading a steady-state floor for never callingmemory.growagain. A smaller binary does not imply a smaller runtime footprint.
Every row is reproducible from a clean checkout, but the machine is a developer laptop: treat the ratios as the signal and re-run zig build bench on your own hardware before quoting an absolute number. Full method, and what is deliberately not measured, in bench/README.md.
tools/rego2ast.py converts opa parse --format json output into zopa's AST, and refuses -- loudly -- anything it cannot express. zig build test-coverage walks a corpus of one-construct policies and records what converts, so this is a table rather than an adjective. Currently 39 of 54. What is missing:
| Not supported | Why it matters |
|---|---|
some x without in, wildcard refs (input.xs[_]) |
zopa binds names by iteration and has no unification. some x in xs and some k, v in xs convert. |
sprintf, lower, split, and every builtin outside the four |
Only startswith, endswith, contains, count exist. |
| array and set comprehensions | No comprehension support at all. |
destructuring assignment ([a, b] := ...) |
Bind the whole value and index into it. |
references to other rules or to data (allow if is_admin) |
zopa has no rule-to-rule references or data document; the name would be read from the input. |
| user-defined functions, definition or call | Inline the body. A definition's parameters would resolve against the input rather than bind. |
else fallback branches |
The fallback would be dropped, leaving only the first condition. |
with input.y as ... |
It would change the input the body sees, and zopa has no equivalent. |
partial rules -- both deny contains msg if ... and p[k] = v if ... |
zopa rules are complete: one name, one value. |
Four of these are worth reading twice if you have used zopa before v0.4.1. with, partial rules, else branches and function definitions all converted successfully while emitting an AST that answered a different question than the Rego it came from -- a dropped modifier, a discarded key, a lost fallback, a parameter silently reinterpreted as an input field. They now refuse, and each has a conformance fixture built to fail rather than skip if the silent behaviour returns. Converting is not the same as deciding correctly -- zig build test-conformance covers that, driving real opa parse output through the module and comparing decisions.
Size, and what it actually buys. A release build is around 75 KB, and it is the same 75 KB no matter how many policies you run through it. opa build -t wasm produces 134 KB for a one-line policy and 149 KB for a sixty-rule one -- roughly 1.8-2x zopa per module, and one module per policy rather than one for the fleet. That is a real advantage but a narrower one than this README used to claim: the ~30 MB figure often quoted for "OPA in WASM" is the OPA binary (40 MB here), not what its WASM backend emits. Cedar and Casbin don't ship as wasm modules at all.
Allocation profile. Every evaluation runs against a single std.heap.ArenaAllocator that is reset with .retain_capacity after each call. After a brief warm-up, memory.grow doesn't fire again -- the wasm linear memory footprint stays flat regardless of throughput.
proxy-wasm native. proxy_on_request_headers runs the allow target rule; proxy_on_request_body and proxy_on_response_headers fire allow_body / allow_response when present. Lifecycle exports are first-class. The repo ships an Envoy bootstrap (examples/envoy/) exercised in CI against a real Envoy.
Fails closed. Every path that can't reach a decision denies: no policy, a policy that won't parse, a host call that errors, a body larger than the buffer cap. An authorization filter that fails open is worse than no filter, because the deployment believes it is protected.
No DSL to learn. zopa accepts a Rego-flavored AST as JSON. Use OPA's compiler to produce it (tools/rego2ast.py covers the v1 subset against opa parse --format json); zopa runs it. The wasm module is the runtime, not the language.
Standards-shaped input. An OpenID AuthZEN Access Evaluation request is already a valid zopa input -- no adapter, no field renaming. See docs/authzen.md.
No external dependencies. Just Zig 0.17+ stdlib. The whole code fits in src/ and reads top-to-bottom.
Reaching for the wrong tool costs more than the 75 KB saves:
- You need the Rego language, not a subset. Comprehensions,
http.send, partial evaluation, most builtins -- none of that is here. Run OPA. - You need a management plane. Bundle distribution, decision logs, status APIs, policy hot-reload from a server. That is what OPA is for; zopa is a decision function with a configure hook.
- You need explanations, not decisions. zopa returns a boolean. It can't tell you which rule fired or why.
- Your filter is body-heavy and single-tenant. Envoy dynamic modules run native in-process with no VM and no serialisation, which is faster. You give up the sandbox and pin the build to an Envoy version. If the isolation boundary isn't buying you anything, take the speed.
- You want a drop-in OPA replacement. zopa answers a narrower question than OPA does, on purpose.
| Export | Signature | Purpose |
|---|---|---|
malloc |
(len) -> ptr |
Allocate a buffer the host owns. |
proxy_on_memory_allocate |
(len) -> ptr |
Same allocator under the name proxy-wasm vNEXT hosts probe for. |
free |
(ptr) |
Release a buffer from malloc. The length lives in a prefix. |
evaluate |
(input, ast) -> i32 |
Decide allow in the default package. |
evaluate_target |
(input, ast, rule) -> i32 |
Decide a named rule: allow_body, allow_response, or your own. |
evaluate_addressed |
(input, ast, package, rule) -> i32 |
Decide package.rule inside a modules bundle. |
policy_compile |
(ast) -> i32 |
Build a policy once and get a handle. -1 if it will not build. |
policy_release |
(handle) -> i32 |
Free a compiled policy. 1 if it was live, 0 if not. |
evaluate_compiled |
(handle, input) -> i32 |
Decide allow against a held policy. |
evaluate_compiled_addressed |
(handle, input, package, rule) -> i32 |
Decide package.rule against a held policy. |
The five decision exports return 1 (allow), 0 (deny), or -1 (error). Treat -1 as deny; it means the input or policy could not be evaluated, which is never a grant. A handle that was never issued, or has already been released, is an error and therefore denies -- including after its slot has been reused by a later policy_compile, since a handle carries the generation of the slot it was issued for as well as its index.
Compile once if you serve traffic. evaluate is handed the AST on every call and cannot know it is the same one as last time, so it re-parses and rebuilds the policy each request -- on the benchmark's RBAC fixture that is 4.7 µs of 6.11. policy_compile builds it onto its own arena and hands back a handle; evaluate_compiled then does the input parse and the rule walk and nothing else. The host owns the handle and must policy_release it; nothing in the module can know when you are done, so a handle you drop leaks the policy for the life of the module, exactly like a malloc you never free. This is the arrangement the proxy-wasm path has always used internally.
Buffers passed in must stay alive for the duration of the call -- string values in the parsed tree alias them rather than being copied.
http_filters:
- name: envoy.filters.http.wasm
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
config:
configuration:
"@type": type.googleapis.com/google.protobuf.StringValue
value: |
{"type":"module","rules":[
{"type":"rule","name":"allow","default":true,
"value":{"type":"value","value":false}},
{"type":"rule","name":"allow","body":[
{"type":"eq",
"left":{"type":"ref","path":["input","method"]},
"right":{"type":"value","value":"GET"}}]}
]}
vm_config:
runtime: envoy.wasm.runtime.v8 # or .wamr / .wasmtime
code:
local:
filename: /etc/zopa/zopa.wasmA complete bootstrap with end-to-end test runner is in examples/envoy/.
The AST is Rego-shaped JSON. Full reference: docs/ast.md.
{ "type": "module", "rules": [
{ "type": "rule", "name": "allow", "default": true,
"value": { "type": "value", "value": false } },
{ "type": "rule", "name": "allow", "body": [
{ "type": "eq",
"left": { "type": "ref", "path": ["input", "user", "role"] },
"right": { "type": "value", "value": "admin" } }
]},
{ "type": "rule", "name": "allow", "body": [
{ "type": "every", "var": "p",
"source": { "type": "ref", "path": ["input", "required_perms"] },
"body": {
"type": "some", "var": "g",
"source": { "type": "ref", "path": ["input", "user", "perms"] },
"body": { "type": "eq",
"left": { "type": "ref", "path": ["g"] },
"right": { "type": "ref", "path": ["p"] } } } }
]}
]}Supported nodes: value, ref, assign, compare (eq/neq/lt/lte/gt/gte), not, set, some, every, in, call, module, modules, rule. The type field accepts shorthand for compare ops ({"type": "eq", ...} is the same as {"type": "compare", "op": "eq", ...}).
Builtin functions surfaced via call: startswith, endswith, contains, count. Object iteration supports kind: "keys" (default) or "values" on some / every, and their body may be a statement list. Multi-package bundles use {"type": "modules", "modules": [...]} and dispatch via evaluate_addressed(input, ast, package, rule).
host wasm (zopa)
+----------+ malloc(n) +-----------------+
| Envoy / | -----------------> | host_allocator |
| any | <----------------- | (length-prefix)|
| runtime | ptr +-----------------+
| |
| | evaluate(in,ast) +-----------------+
| | -----------------> | request arena |
| | | json.parse |
| | | ast.build |
| | <----------------- | evalBundle |
| | 1 / 0 / -1 | arena.reset |
+----------+ +-----------------+
host_allocator (std.heap.wasm_allocator) lives for the module's lifetime and backs every host-visible buffer. The request arena is allocated on top of it and reset at the end of every evaluate(), including the proxy-wasm callback path.
The proxy-wasm path adds one thing to the picture: the policy is parsed and built once in proxy_on_configure, onto a second long-lived arena, and kept. Per-request work there is the input parse plus the rule walk -- ast.build does not run again until the filter is reconfigured.
More detail in docs/architecture.md.
You need Zig 0.17.0:
brew install zig # or download from ziglang.org
zig build # debug build
zig build --release=small # ~75 KB optimized .wasmThe artifact is zig-out/bin/zopa.wasm.
The same policies run under every host zopa claims to support, because "it works in Node" says nothing about the proxy-wasm ABI. None of the hosts are required locally; pick what's installed. CI runs all of them.
zig build test-unit # Zig host-side unit tests, incl. fuzz smoke runs
zig build test # Node.js integration (needs node 18+)
zig build test-wasmtime # wasmtime via Python (see test/requirements.txt)
zig build test-envoy # real Envoy: proxy-wasm ABI, body buffering, phases
zig build test-conformance # `opa parse` + tools/rego2ast.py + zopa
zig build bench # latency benchmark
zig build test-all # everything availableSetup for the Python suites:
python3 -m venv .venv-test
.venv-test/bin/pip install -r test/requirements.txtzig build test-envoy is the only suite that exercises proxy-wasm itself -- configure, the three phase callbacks, body buffering, and send_local_response. Everything else calls evaluate directly and would keep passing with a broken shim.
| OPA | Cedar | Casbin | zopa | |
|---|---|---|---|---|
| Language | Go | Rust | Go (+ ports) | Zig |
| Released as wasm | Yes (~134 KB per policy) | No | No | Yes (~75 KB, all policies) |
| Allocation model | GC | RC + arenas | GC | per-request arena |
| proxy-wasm | Side project | No | No | First-class |
| Policy input | Rego source | Cedar source | CSV / source | Compiled AST (Rego-shaped) |
| Maturity | CNCF Graduated | Stable | Mature | Alpha |
zopa is not a replacement for OPA when you need the full Rego language, the management plane, or bundles. It's a drop-in for the narrow case where you've already compiled the policy and want to evaluate it inside a proxy-wasm filter without a 40 MB sidecar.
Do I have to write the AST by hand? No. Write Rego, run opa parse --format json, and pipe it through tools/rego2ast.py. Hand-writing the AST is for tests and one-liners.
What happens if my Rego uses something zopa doesn't support? rego2ast.py refuses to convert it rather than emitting something that evaluates differently. The conformance runner records that as a SKIP, not a pass. There is no silent degradation.
Is it really zero-allocation? Not literally -- it allocates from an arena. What it doesn't do is grow linear memory in steady state: the arena is reset with .retain_capacity after every evaluation, so once the high-water mark is reached, memory.grow stops firing. There is no GC and nothing to tune.
What does it do when something goes wrong? Denies. Unparseable input, a policy that won't build, a host call that fails, a request body bigger than the 64 KiB buffer cap -- all deny. The one place this is subtle is the body cap: a truncated body is refused outright rather than evaluated against the prefix, because a prefix that fails to parse would make a deny rule silently miss.
Can I run more than one policy in a VM? Yes -- bundle them as {"type":"modules","modules":[...]} and address (package, rule) with evaluate_addressed. What you can't do today is give two Envoy filters sharing an explicit vm_id different policies; the last configure wins. See ROADMAP.
How does it handle a request body? Only if the policy has an allow_body rule. Without one, the body callback returns immediately and nothing is buffered. With one, the body is accumulated until end of stream and evaluated as {"body": ..., "body_raw": ..., "body_truncated": ...}.
Is the alpha label real? Yes. The engine is tested but the public surface will move: export names, AST schema, and callback semantics are all still in play before 1.0. Pin a tag.
Why Zig? Freestanding wasm with no runtime, no GC, and no allocator you didn't ask for, plus explicit allocator passing -- which is what makes the "one arena per request, reset at the end" model expressible at all.
See ROADMAP.md. Streaming evaluation runtime, proxy-wasm 0.3.x migration, and expanding the OPA conformance corpus are the next big items.
CONTRIBUTING.md covers local setup, code style, DCO, and PR expectations.
SECURITY.md. Use GitHub's private vulnerability reporting; don't open a public issue for security bugs.
zopa would not exist without:
- Open Policy Agent for the Rego language and reference implementation.
- Cedar for the example of a small, focused authorization language.
- proxy-wasm/spec and the Envoy team for the ABI.
