WASM plugin development
This guide explains how to create WASM plugins for Barbacane.
Overview
Barbacane plugins are WebAssembly (WASM) modules that extend gateway functionality. There are two types:
| Type | Purpose | Exports |
|---|---|---|
| Middleware | Process requests/responses in a chain | init, on_request, on_response |
| Dispatcher | Handle requests and generate responses | init, dispatch |
Prerequisites
- Rust stable with
wasm32-unknown-unknowntarget barbacane-plugin-sdkcrate
# Add the WASM target
rustup target add wasm32-unknown-unknown
Quick Start
1. Create a New Plugin
cargo new --lib my-plugin
cd my-plugin
2. Configure Cargo.toml
[package]
name = "my-plugin"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
barbacane-plugin-sdk = { path = "../path/to/barbacane/crates/barbacane-plugin-sdk" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
3. Write the Plugin
Middleware example:
use barbacane_plugin_sdk::prelude::*;
use serde::Deserialize;
#[barbacane_middleware]
#[derive(Deserialize)]
pub struct MyMiddleware {
// Configuration fields from the spec
header_name: String,
header_value: String,
}
impl MyMiddleware {
pub fn on_request(&mut self, req: Request) -> Action {
// Add a header to the request
let mut req = req;
req.headers.insert(
self.header_name.clone(),
self.header_value.clone(),
);
Action::Continue(req)
}
pub fn on_response(&mut self, resp: Response) -> Response {
// Pass through unchanged
resp
}
}
Dispatcher example:
use barbacane_plugin_sdk::prelude::*;
use serde::Deserialize;
#[barbacane_dispatcher]
#[derive(Deserialize)]
pub struct MyDispatcher {
status: u16,
body: String,
}
impl MyDispatcher {
pub fn dispatch(&mut self, _req: Request) -> Response {
Response::text(self.status, Default::default(), &self.body)
}
}
4. Create plugin.toml
[plugin]
name = "my-plugin"
version = "0.1.0"
type = "middleware" # or "dispatcher"
category = "traffic-control"
# implements = ["http:bearer"] # authentication plugins only
description = "My custom plugin"
wasm = "my_plugin.wasm"
[capabilities]
host_functions = ["log"]
# Optional: see Resource Limits.
# [limits]
# memory_mib = 4
category is the plugin’s family. It groups the plugin in the middleware guide,
and authentication additionally tells the compiler that the plugin verifies a
client credential. Current values: authentication, authorization, caching,
observability, traffic-control, transformation for middleware;
proxy, messaging, cloud, testing for dispatchers.
5. Create config-schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["header_name", "header_value"],
"properties": {
"header_name": {
"type": "string",
"description": "Header name to add"
},
"header_value": {
"type": "string",
"description": "Header value to set"
}
}
}
Mark any field that carries a secret (API key, password, token, client secret)
with "writeOnly": true — the standard JSON Schema keyword for sensitive
values:
"api_key": {
"type": "string",
"writeOnly": true,
"description": "Provider API key. Use a secret reference (env://VAR or file://...)."
}
barbacane compile then warns (E1070) — and the vacuum linter flags — when
such a field is set to a plaintext literal instead of an env:// / file://
reference, so credentials are never baked into the compiled artifact. The
detection is nested-aware (arrays and maps of objects). Do not mark
non-secret fields (e.g. a message-key expression) writeOnly.
Declaring the request headers your plugin reads
A request carries only the headers its operation admits, and everything else is
dropped before on_request runs. If your plugin reads a header and does not
say so here, it will find nothing.
Mark the field whose value names a header with the format that matches how
the value is written:
format | The field holds | Example |
|---|---|---|
header-name | a header name, or a list of them | apikey-auth.header_name, cache.vary |
header-ref | a selector that may name a header among other things | rate-limit.partition_key (header:x-tenant), kafka.key ($request.header.x-order-id) |
header-name-map | an object whose keys are header names | request-transformer.headers.rename |
"header_name": {
"type": "string",
"format": "header-name",
"default": "X-API-Key",
"description": "Header to read the key from"
}
A default is collected too, since it is the header the plugin reads when the
configuration leaves the field out.
Names are matched case-insensitively. The x-auth-* namespace belongs to the
auth plugins’ output, so naming one is a compile error (E1056).
A plugin that verifies a client credential reads its header from the spec
instead. Set category = "authentication" in plugin.toml, and the compiler
then requires every operation using the plugin to name the security scheme
carrying the credential (E1057), which is what admits the header.
Such a plugin also says which kinds of credential it reads, so a document pairing it with a scheme it cannot read is refused (E1032) rather than rejecting every request at runtime:
[plugin]
category = "authentication"
implements = ["http:bearer", "oauth2", "openIdConnect"]
The tokens name security scheme types: apiKey, http:<scheme> (http:basic,
http:bearer), oauth2 and openIdConnect. An http scheme is qualified by
its authentication scheme, since reading Basic credentials is not reading a
Bearer token. Matching is case-insensitive, and one match among the schemes an
operation names is enough. Leaving implements out exempts the plugin from the
check.
Schemes the connection carries have no token, since no middleware reads one off
a request: mutualTLS, whose certificate is presented during the TLS handshake,
and AsyncAPI’s broker mechanisms (X509, the SCRAM pair, gssapi, plain,
userPassword). They take no part in the match, so an operation naming one
alongside a request credential is judged on the request credential alone.
The SDK macros embed config-schema.json into the .wasm, as they already do
plugin.toml, so these annotations reach the compiler wherever the binary
travels and no sidecar file has to accompany it. Rebuild the plugin after
editing either file, or the compiler reads the copy embedded by the previous
build.
After changing config-schema.json, regenerate the vacuum ruleset validators
(node docs/rulesets/generate.mjs) and run docs/rulesets/tests/run-tests.sh.
6. Build
cargo build --target wasm32-unknown-unknown --release
cp target/wasm32-unknown-unknown/release/my_plugin.wasm .
Plugin SDK Types
The SDK’s data types are #[non_exhaustive]: a minor release may add a field, so build them with their constructors, not as struct literals. Their fields are public to read and assign.
Request
#[non_exhaustive]
pub struct Request {
pub method: String,
pub path: String,
pub query: Option<String>,
pub headers: BTreeMap<String, String>,
pub body: Option<Vec<u8>>, // binary-safe, travels via side-channel
pub client_ip: String,
pub path_params: BTreeMap<String, String>,
}
Build one with Request::new(method, path) and with_query, with_header, with_body, with_client_ip, with_path_param. Helper methods: body_str() -> Option<&str>, body_string() -> Option<String>, set_body_text(&str).
Response
#[non_exhaustive]
pub struct Response {
pub status: u16,
pub headers: BTreeMap<String, String>,
pub body: Option<Vec<u8>>, // binary-safe, travels via side-channel
}
Build one with Response::new(status) and with_header, with_headers, with_body, or Response::text(status, headers, &str); Response::default() is an empty 200. Helper methods: body_str() -> Option<&str>, set_body_text(&str).
let denied = Response::new(403)
.with_header("content-type", "application/problem+json")
.with_body(br#"{"type":"urn:barbacane:error:acl-denied","title":"Forbidden","status":403}"#.to_vec());
The error enums (http::HttpError, ldap::LdapError, jwt::JwtDecodeError) are #[non_exhaustive] too: a match on one needs a _ arm.
Note: Bodies travel as raw bytes via side-channel host functions (
host_body_read/host_body_set), not embedded in JSON. The proc macros handle this transparently — plugin authors just read and writerequest.body/response.bodyasOption<Vec<u8>>. This design (matching proxy-wasm and http-wasm) avoids the ~3.65× memory overhead of base64 encoding, allowing 10MB+ bodies within the default 16MB WASM memory limit.
Action (Middleware only)
pub enum Action {
/// Continue to next middleware/dispatcher with (possibly modified) request
Continue(Request),
/// Short-circuit the chain and return this response immediately
ShortCircuit(Response),
}
Host Functions
Plugins can call host functions to access gateway capabilities. Declare required capabilities in plugin.toml:
The SDK wraps the most common host functions so you don’t hand-roll the FFI:
barbacane_plugin_sdk::log, ::http, ::context, ::ldap,
::errors::ProblemDetails, and ::jwt. Each has a native (non-wasm) stub so
your plugin still compiles and unit-tests off-target (context keeps a
thread-local map natively, so tests can set and read values). You still
declare the underlying capability in plugin.toml.
Request context
[capabilities]
host_functions = ["context_get", "context_set"]
use barbacane_plugin_sdk::context;
// An auth plugin publishes the verified identity for the rest of the chain.
context::set(context::AUTH_SUB, "alice");
context::set(context::AUTH_GROUPS, "admin,editor");
// A later middleware reads it; unlike a header, a client cannot supply it.
let consumer = context::get(context::AUTH_SUB);
Logging
[capabilities]
host_functions = ["log"]
use barbacane_plugin_sdk::log;
log::info("Processing request");
log::warn("rate limit exceeded");
log::error("something went wrong");
// or an explicit level: log::log(log::Level::Debug, "verbose detail");
HTTP Calls (Dispatcher only)
[capabilities]
host_functions = ["http_call"]
use barbacane_plugin_sdk::http;
let req = http::HttpRequest::new("GET", "https://api.example.com")
.header("accept", "application/json")
.timeout_ms(5000);
// The optional request body is passed separately (sent via the side-channel):
match http::call(&req, None) {
Ok(resp) => {
let _status = resp.status;
let _body = resp.body_str(); // Option<&str>
}
Err(e) => { /* http::HttpError: Unreachable / Empty / ReadFailed / ... */ }
}
.tls(http::TlsSettings { client_cert, client_key, ca }) sets a client
certificate for mutual TLS and a CA the server must chain to. Each is a path to
a PEM file, which the host reads only from under BARBACANE_SECRETS_DIR; with
ca, the built-in roots are not trusted. HttpRequest implements Default, so
a struct literal can end with ..Default::default().
http::pool_call sends a request to one of request.endpoints, which the host
selects and retries as the http-upstream endpoints
describe; request.url then holds the path and query. It needs the http_pool
capability.
The host sets Host from the URL and owns the message framing, so it drops
these headers when a plugin sets them, on every call, pooled or streamed:
Host, Content-Length, Transfer-Encoding, Connection, Keep-Alive,
Proxy-Connection, Upgrade, TE and Trailer. Authorization is sent as
set.
Hashing
[capabilities]
host_functions = ["hash"]
use barbacane_plugin_sdk::hash;
let digest: [u8; 32] = hash::sha256(body);
let hex: String = hash::sha256_hex(body); // 64 lowercase hex digits
The host computes the digest. Hashing in WASM costs fuel for every byte, and a call’s budget does not grow with the request body, so hash a body this way rather than with a crate compiled into the plugin. In a plugin’s unit tests the same functions hash in-process.
Error responses (RFC 9457 problem+json)
Build consistent application/problem+json error responses with the shared builder:
use barbacane_plugin_sdk::errors::ProblemDetails;
return Action::ShortCircuit(
ProblemDetails::new(403, "urn:barbacane:error:authorization-failed", "Forbidden")
.detail("Access denied")
.with("consumer", "alice") // optional extension members
.into_response(),
);
JWT parsing (auth plugins)
use barbacane_plugin_sdk::jwt;
if let Some(token) = jwt::bearer_token(auth_header) {
// Decode claims for inspection — signature is verified separately
// (host `verify_signature` capability), not by this helper.
let claims: MyClaims = jwt::decode_claims_unverified(token)?;
if claims.aud.contains("my-api") { /* jwt::Audience: string or array */ }
}
Metrics (host imports)
With the telemetry capability, host_metric_counter_inc(name, labels, value) and host_metric_histogram_observe(name, labels, value) record a metric, labels being a JSON object such as {"status": 200}. The gateway exports it as barbacane_plugin_<plugin>_<name> with those labels; observe histograms in seconds. Keep labels bounded: a value per request, such as a duration or an ID, makes a series per request, and each plugin may create 1,000. The observability guide gives the naming rules and what is refused.
The same capability grants host_span_start(name), host_span_end() and host_span_set_attribute(key, value). The gateway records them as debug log events and answers host_span_start with the id 1; they do not create spans in the request’s trace.
Clock, secrets (host imports)
With the clock_now capability, barbacane_plugin_sdk::clock::now_ms() reads a
monotonic clock in milliseconds (only differences are meaningful) and
clock::unix_time() the seconds since the Unix epoch. Secrets have no SDK
wrapper: declare get_secret and import host_get_secret directly (see
oidc-auth for the extern "C" binding pattern).
[capabilities]
host_functions = ["clock_now", "get_secret"]
Secrets are resolved at gateway startup from env:// / file:// references, so
get_secret returns the resolved value (never a plaintext literal baked into the
artifact).
LDAP (host imports)
[capabilities]
host_functions = ["ldap"]
host_ldap_bind(req_ptr, req_len) -> i32 verifies a DN and password with a
simple bind on a fresh connection. An empty password is refused as
invalid_credentials without contacting the directory, since a DN with an
empty password is an unauthenticated bind (RFC 4513 §5.1.2) that proves
nothing; host_ldap_search(req_ptr, req_len) -> i32
runs a search on a pooled connection bound as the service account named in the
request. Both take a JSON request carrying url, bind_dn, password,
starttls, allow_plaintext and timeout_ms (search adds base_dn, scope,
filter, attributes, size_limit). They return the result length, or -1
on an ABI error (bad pointer, unparseable request, no client); check for -1
before calling host_ldap_read_result(buf_ptr, buf_len) to read the JSON
result. The result’s code field (invalid_credentials, connection_failed,
timeout, plaintext_refused, …) tells a rejected credential apart from a
directory failure. A password crosses a plaintext ldap:// connection only
when allow_plaintext is set. Escape any user-supplied value per RFC 4515
before placing it in a filter. See
ADR-0032 for the design.
WASI
A plugin imports the barbacane host functions above and, from
wasi_snapshot_preview1, only these WASI functions:
| Function | What the host does |
|---|---|
random_get | Fills the buffer from the host’s CSPRNG |
clock_time_get | Writes the current time |
fd_write | Accepts the write and discards it |
sched_yield | Returns immediately |
environ_get, environ_sizes_get | Report an empty environment |
proc_exit | Traps |
A plugin importing any other function, from WASI or another module, fails
compilation with E1043, and the data plane refuses to load it. The error
names the import and lists this set.
Building for wasm32-unknown-unknown, as the quick start does, imports no
WASI at all. wasm32-wasip1 also works while the plugin stays inside the set:
randomness (getrandom, HashMap), the clock, and println! are covered, but
reading files, environment variables or command-line arguments, and threads,
are not. To see what a build imports, run
wasm-tools print my_plugin.wasm | grep import.
ABI version
The plugin ABI is the set of exports the gateway calls (memory, alloc, init, and on_request and on_response or dispatch), the host functions above with their signatures, and the WASI functions. It has a version, 1. The SDK macros embed it in a barbacane_abi custom section (a little-endian u32, barbacane_plugin_sdk::ABI_VERSION); the compiler refuses a plugin without the section or built for another version (E1045), and the data plane refuses it again when it loads an artifact. A plugin built with an SDK before 1.0 carries no section: rebuild it.
A minor release may add host functions, capabilities and exports it calls when present; it keeps the version at 1. The version changes only when a plugin built for the previous one would no longer run, which is a major release of Barbacane.
Deprecated host functions
A host function on its way out stays importable until the release named here, and a plugin importing it compiles with the warning E1016 and loads with a warning in the gateway’s log.
| Function | Use instead | Removed in |
|---|---|---|
host_time_now | host_clock_now (clock::now_ms() in the SDK) | 1.2.0 at the earliest |
Using Plugins in Specs
Declare in barbacane.yaml
Plugins can be sourced from a local path or a remote URL:
plugins:
# Local path (development)
my-plugin:
path: ./plugins/my_plugin.wasm
# Remote URL (production, CI/CD)
jwt-auth:
url: https://github.com/barbacane-dev/barbacane/releases/download/v0.5.2/jwt-auth.wasm
sha256: abc123... # optional integrity check
Remote plugins are downloaded at compile time and cached at ~/.barbacane/cache/plugins/. Use --no-cache to bypass the cache entirely (re-download without caching).
Use in OpenAPI spec
As middleware:
paths:
/users:
get:
x-barbacane-middlewares:
- name: my-plugin
config:
header_name: "X-Custom"
header_value: "hello"
As dispatcher:
paths:
/mock:
get:
x-barbacane-dispatch:
name: my-plugin
config:
status: 200
body: '{"message": "Hello"}'
Testing Plugins
Unit Testing
Test your plugin logic directly:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_adds_header() {
let mut plugin = MyMiddleware {
header_name: "X-Test".to_string(),
header_value: "value".to_string(),
};
let req = Request::new("GET", "/test");
let action = plugin.on_request(req);
match action {
Action::Continue(req) => {
assert_eq!(req.headers.get("X-Test"), Some(&"value".to_string()));
}
_ => panic!("Expected Continue"),
}
}
}
Integration Testing
Use fixture specs with barbacane-test:
use barbacane_test::TestGateway;
#[tokio::test]
async fn test_my_plugin() {
let gw = TestGateway::from_spec("tests/fixtures/my-plugin-test.yaml")
.await
.unwrap();
let resp = gw.get("/test").await.unwrap();
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers().get("X-Test"), Some("value"));
}
Official Plugins
Barbacane includes these 29 official plugins in the plugins/ directory:
| Plugin | Type | Description |
|---|---|---|
mock | Dispatcher | Return static responses |
http-upstream | Dispatcher | Reverse proxy to HTTP backends, with load balancing and upstream TLS |
lambda | Dispatcher | Invoke AWS Lambda functions |
kafka | Dispatcher | Publish messages to Kafka |
nats | Dispatcher | Publish messages to NATS |
s3 | Dispatcher | S3 / S3-compatible object storage proxy with SigV4 signing |
ws-upstream | Dispatcher | WebSocket proxy, with the middleware chain run on the upgrade |
fire-and-forget | Dispatcher | Forward the request and answer with a static response at once |
jwt-auth | Middleware | JWT token validation |
apikey-auth | Middleware | API key authentication |
basic-auth | Middleware | HTTP Basic authentication |
oauth2-auth | Middleware | OAuth2 token introspection |
oidc-auth | Middleware | OpenID Connect token validation against a JWKS |
ldap-auth | Middleware | LDAP / Active Directory authentication (directory bind, group lookup) |
acl | Middleware | Group and consumer access control |
opa-authz | Middleware | Authorization decisions from an OPA server |
cel | Middleware | CEL policy evaluation and policy-driven routing |
rate-limit | Middleware | Sliding window rate limiting |
request-size-limit | Middleware | Request body size limits |
ip-restriction | Middleware | IP allowlist/blocklist |
bot-detection | Middleware | Block bots by User-Agent pattern |
redirect | Middleware | HTTP redirects |
cache | Middleware | Response caching |
request-transformer | Middleware | Header, query, path and body transformations before dispatch |
response-transformer | Middleware | Status, header and body transformations before delivery |
cors | Middleware | CORS header management |
correlation-id | Middleware | Request correlation ID propagation |
observability | Middleware | SLO monitoring and detailed logging |
http-log | Middleware | Ship request logs to an HTTP endpoint |
Use these as references for your own plugins.
Best Practices
- Keep plugins focused - One plugin, one responsibility
- Validate configuration - Use JSON Schema to catch config errors at compile time
- Handle errors gracefully - Return appropriate error responses, don’t panic
- Document capabilities - Only declare host functions you actually use
- Test thoroughly - Unit test logic, integration test with the gateway
- Use semantic versioning - Follow semver for plugin versions
Instances and state
init(config) runs once for each plugin and config in the artifact. The gateway
keeps what init left in the plugin’s linear memory, and every request then
runs in a new instance whose memory starts from that state. So:
- whatever
initbuilds from the config (parsed rules, compiled patterns) is there for every request, without being rebuilt; - nothing a request writes reaches another request: each instance is discarded
when its request ends, and the next one starts from the state
initleft.
A plugin keeps no state between requests. State that must outlive a request lives on the host: the rate limiter, the response cache, a context value for later middlewares in the same request.
The gateway restores linear memory only, so init must leave everything else
as the module defined it. A module qualifies when it imports no global, defines
at most one mutable global (the stack pointer, which a call leaves as it found
it), and changes no table or passive data segment. Plugins built with the SDK
for wasm32-unknown-unknown qualify. Any other module still works: it runs
init for each request instead.
Resource Limits
Each instance of a plugin runs with its own limits. A plugin declares them in a
[limits] table in plugin.toml; a limit it leaves out takes the default.
[limits]
memory_mib = 4 # linear memory, in MiB
fuel = 20_000_000 # fuel for one call
timeout_ms = 50 # wall-clock budget for one call, in ms
| Limit | Key | Default | Ceiling |
|---|---|---|---|
| Linear memory | memory_mib | 16 MiB | 1024 MiB |
| Fuel per call | fuel | 100,000,000 | 10,000,000,000 |
| Wall clock per call | timeout_ms | 100 ms | 10,000 ms |
| Stack | (not declared) | 1 MiB |
The wall clock restarts after each host function that waits on the network, so
that wait does not count. A key outside the table above, a value below 1 or a value
above its ceiling fails compilation with E1044, and the data plane refuses an
artifact that records one.
A plugin that receives bodies, a dispatcher or a middleware with
body_access = true, gets at least max_body_size plus 4 MiB of memory, so a
body fits beside its working memory. A middleware without body_access keeps
its own memory limit whatever max_body_size is.
The operator can set limits in place of the plugin’s, key by key, in
barbacane.yaml or on the control plane’s project plugin, within the same
ceilings: see the project manifest.
The limits in effect are recorded in the artifact with the plugin’s
capabilities and covered by artifact_hash, so they cannot change after the
artifact is signed.
Exceeding a limit results in a trap, which answers the request with a 500. On a streamed response, on_response runs after the response is sent, so a trap there is logged and the response is unaffected.
Troubleshooting
Plugin not found
Ensure the plugin is declared in barbacane.yaml and the WASM file exists at the specified path.
Config validation failed
Check that your plugin’s configuration in the OpenAPI spec matches the JSON Schema in config-schema.json.
WASM trap
Your plugin exceeded resource limits or panicked. Check logs for details. Common causes:
- Infinite loops
- Large memory allocations
- Unhandled errors causing panic
Unknown capability
You’re using a host function not declared in plugin.toml. Add it to capabilities.host_functions.
Unsupported import (E1043)
The plugin imports a function the gateway does not provide, usually a WASI
function such as fd_close or args_get pulled in by the standard library on
wasm32-wasip1. Build for wasm32-unknown-unknown, or remove the code that
needs it; see WASI for the supported set.
Distributing Plugins
GitHub Releases
The recommended way to distribute plugins is as GitHub release assets. Upload both the .wasm binary and plugin.toml alongside your release:
my-plugin.wasm
my-plugin.plugin.toml
Generate checksums for integrity verification:
sha256sum my-plugin.wasm > checksums.txt
Users reference your plugin by URL in their barbacane.yaml:
plugins:
my-plugin:
url: https://github.com/your-org/my-plugin/releases/download/v1.0.0/my-plugin.wasm
sha256: <from checksums.txt>
Official Plugins
All official Barbacane plugins are published as release assets on every tagged release. Pre-built .wasm files and checksums (plugin-checksums.txt) are available at:
https://github.com/barbacane-dev/barbacane/releases/download/v<VERSION>/<plugin-name>.wasm
Plugin Metadata Discovery
When resolving a url: source, the compiler attempts to fetch plugin.toml from sibling URLs to extract version and type metadata:
<name>.plugin.toml(same directory as the.wasm)plugin.toml(parent directory)
If neither is found, the plugin still works but without version/type metadata in the artifact manifest.