Docs / Custom Plugins

Custom Plugin Development

Extend Ferrum Edge with custom plugins written in Rust. Drop a .rs file in custom_plugins/ and it is auto-discovered, compiled into the binary, and available by name at runtime.

Overview

Custom plugins are plain Rust files compiled directly into the gateway binary — no external SDK, no FFI, no dynamic loading. They implement the Plugin trait from crate::plugins and are registered automatically by a build script that scans the custom_plugins/ directory.

The file name (without .rs) becomes the plugin name used in gateway configuration. For example, my_rate_limiter.rs registers as plugin name "my_rate_limiter". A file name that matches a built-in plugin (such as cors.rs) fails the build.

A custom plugin runs in-process with the gateway's privileges: it can read the traffic it is attached to, resolved secrets, and the process environment. Review plugin source the way you would review a change to the gateway itself, and keep custom_plugins/ under the same access control as the rest of the repository.

Quick Start

1

Create the plugin file

bash
touch custom_plugins/my_plugin.rs
2

Implement the Plugin trait

See the full example below. Implement name(), declare response-body production, and export the three required functions: create_plugin(), failure_policy(), and config_contract(). Override priority() when needed; its default is 5000.

3

Build and test — your plugin is compiled in

bash
cargo build --release
# Check your config_contract() examples with the plugin config sweep
cargo test --test unit_plugins_b_tests plugin_config_closure

The build script discovers the file, declares the module, and registers it in the plugin factory. There is no registry to edit.

4

Reference it in your gateway config

Add an entry to plugin_configs; every entry needs a unique id.

json
{
  "id": "my-plugin-1",
  "plugin_name": "my_plugin",
  "enabled": true,
  "scope": "global",
  "config": { "header_value": "ferrum-custom" }
}

Priority Bands

Priority is a u16. Lower values run earlier. Bands are spaced with gaps so future plugins can slot in without renumbering — pick a value in the band that matches where your plugin belongs.

RangeBandPurposeBuilt-in Examples
0–949EarlyMatched-request tracing, IDs, preflight, and short-circuiting before authotel_tracing (25), correlation_id (50), cors (100), request_termination (125), ip_restriction (150), bot_detection (200), grpc_method_router (275), spiffe_identity (940)
950–1999AuthNAuthentication / identity verificationmtls_auth (950), jwks_auth (1000), oauth2_introspection (1050), jwt_auth (1100), key_auth (1200), basic_auth (1300), hmac_auth (1400), soap_ws_security (1500)
2000–2999AdmissionAuthorization, validation, and request admission controlaccess_control (2000), opa (2080), request_size_limiting (2800), rate_limiting (2900), ai_prompt_shield (2925), waf (2930), body_validator (2950), ai_request_guard (2975)
3000–3999TransformRequest shaping and response buffering decisionsrequest_transformer (3000), serverless_function (3025), response_mock (3030), grpc_deadline (3050), request_mirror (3075), response_size_limiting (3490), response_caching (3500)
4000–4999ResponseResponse transformation, compression, security headers, and AI accountingresponse_transformer (4000), compression (4050), ai_federation (4060), ai_token_metrics (4070), security_headers (4080), ai_rate_limiter (4200)
5000CustomDefault for unrecognized / custom plugins—
9000–9999LoggingObservability and frame loggingstdout_logging (9000), statsd_logging (9075), http_logging (9100), kafka_logging (9150), transaction_debugger (9200), prometheus_metrics (9300), api_chargeback (9350)

The default priority is 5000 (the Custom band), which runs after all transforms but before logging — a safe default when your plugin has no strong ordering requirements. Add a named constant to the priority module in src/plugins/mod.rs for discoverability. Operators can also override any instance's priority per plugin-config via priority_override (0–10000).

Plugin Trait Hooks — HTTP/gRPC/WebSocket

HookPhaseCan Reject?Typical Use
on_request_received(&mut ctx) After a route matches and its allowed_methods check passes Yes IP filtering, request validation, early termination
authenticate(&mut ctx, &consumer_index) Authentication Yes Verify identity (JWT, API key, custom tokens)
authorize(&mut ctx) Authorization Yes Check permissions, enforce rate limits
before_proxy(&mut ctx, &mut headers) Pre-backend Yes Transform request headers, add tracing IDs
on_backend_path_resolved(&mut ctx, backend_path) After backend path assembly Yes Route-sensitive policy on the final backend path; opt in with requires_backend_path_resolution()
transform_request_body(&body, content_type, &request_headers) Pre-backend (buffered) No Rewrite request body before sending to backend
on_final_request_body(&headers, &body) Pre-backend (post-transform) Yes Validate the final request body after all transforms
after_proxy(&mut ctx, status, &mut headers) Post-backend Yes Transform response headers, reject responses
on_final_response_headers(&mut ctx, status, &headers) Post-after_proxy No Header-only effects on both buffered and streamed responses
on_response_body(&mut ctx, status, &mut headers, &body) Post-backend (buffered) Yes Inspect buffered response body, extract metrics
transform_response_body(&body, content_type, &headers) Post-backend (buffered) No Rewrite response body before sending to client
on_final_response_body(&mut ctx, status, &headers, &body) Post-backend (post-transform) Yes Validate the final response body after all transforms
response_stream_inspector(&ctx, status, content_type) Post-backend (streaming) Truncate only Inspect a streamed body chunk by chunk without buffering; opt in with requires_response_stream_hooks()
on_response_stream_terminated(&mut ctx, status, outcome) Streaming terminal No Clean up streaming state and record aggregate metadata before logging
log(&summary) Logging No Hand transaction data to a bounded sink. Hooks are awaited in order; buffered responses wait for them, so move slow I/O to a plugin-owned worker
on_ws_frame(proxy_id, connection_id, direction, &message) WebSocket frame Close* Inspect/transform per-frame WebSocket traffic
on_ws_reassembly_frames(proxy_id, connection_id, direction, fragment_frames) WebSocket fragments Close* Meter the wire frames a fragmented message consumed before reassembly

All hooks have default no-op implementations — only override the ones your plugin needs. The table covers the common hooks; the full hook reference adds client body contracts, finalized request egress, backend admission, and final response policy hooks. *WebSocket frame hooks cannot return PluginResult::Reject. Instead, return Some(Message::Close(...)) to close the connection in both directions.

ℹ️
before_proxy header parameter: In before_proxy, always read request headers from the headers parameter, not from ctx.headers. The gateway moves headers out of ctx.headers via std::mem::take() during this call, so ctx.headers is empty. Headers are moved back after the call completes.

Plugin Trait Hooks — TCP/UDP Streams

HookPhaseCan Reject?Typical Use
on_stream_connect(&mut stream_ctx) Connection established Yes Auth, authz, throttling, rate limiting for stream proxies
on_stream_disconnect(&stream_summary) Connection closed No (fire-and-forget) Logging, metrics for stream proxies

For TCP+TLS proxies, on_stream_connect runs after the frontend TLS handshake, so client certificate data is available in StreamConnectionContext.

Capability Methods

These methods tell the gateway about your plugin's requirements. All have default implementations except name(), but custom plugins must override response_body_production(): an undeclared plugin is refused on buffered response paths. The gateway trusts these declarations and enforces composition rules against them, so keep them accurate.

MethodDefaultDescription
name()requiredUnique plugin identifier — must match the file name (without .rs) and config plugin_name
priority()5000Execution order (lower = earlier). See priority bands above.
response_body_production()UndeclaredRequired for custom plugins. Return ResponseBodyProduction::Never unless the plugin replaces response bodies through the bounded body sink
lifecycle_hooks()PluginHooks::ALLOptional. Name the ordinary hooks you override (ON_REQUEST_RECEIVED, BEFORE_PROXY, AFTER_PROXY, LOG) so the gateway skips the rest
supported_protocols()HTTP_ONLY_PROTOCOLSWhich proxy protocols this plugin supports (see protocol constants below)
is_auth_plugin()falseSet to true if your plugin participates in the authentication phase
modifies_request_headers()falseSet to true if your plugin may change request headers in any pre-proxy phase (authenticate, authorize, or before_proxy)
modifies_request_body()falseSet to true if your plugin transforms the request body via transform_request_body()
requires_request_body_before_before_proxy()falseSet to true if your plugin needs the raw request body available during before_proxy()
requires_request_body_buffering()derivedReturns true if the plugin modifies the request body or needs it before authenticate, authorize, or before_proxy. Override for custom logic.
should_buffer_request_body(&ctx)delegatesPer-request decision on whether to buffer. Defaults to requires_request_body_buffering(). Override for conditional buffering.
requires_response_body_buffering()falseSet to true if your plugin needs the entire response body buffered (disables streaming)
applies_after_proxy_on_reject()falseSet to true if your plugin's after_proxy() should also run on gateway-generated rejection responses
requires_ws_frame_hooks()falseSet to true if your plugin implements on_ws_frame() or on_ws_reassembly_frames(). Pre-computed per proxy for zero overhead when unused.
warmup_hostnames()[]Hostnames your plugin connects to — pre-resolved via DNS at startup
tracked_keys_count()NoneNumber of tracked rate-limit keys (for admin API diagnostics)

Protocol Constants

Use these constants in supported_protocols() to declare which proxy protocols your plugin supports:

ConstantProtocolsUse Case
ALL_PROTOCOLSHttp, Grpc, WebSocket, Tcp, UdpProtocol-agnostic plugins (logging, metrics, tracing)
HTTP_FAMILY_PROTOCOLSHttp, Grpc, WebSocketPlugins for all HTTP-based protocols
HTTP_FAMILY_AND_STREAM_PROTOCOLSHttp, Grpc, WebSocket, Tcp, UdpPlugins that authenticate TLS/DTLS client certificates on every transport
HTTP_GRPC_PROTOCOLSHttp, GrpcPlugins for HTTP and gRPC only
HTTP_ONLY_PROTOCOLSHttpHTTP-only plugins (default)
GRPC_ONLY_PROTOCOLSGrpcgRPC-specific plugins
WS_ONLY_PROTOCOLSWebSocketWebSocket frame-level plugins
TCP_ONLY_PROTOCOLSTcpTCP stream-only plugins
UDP_ONLY_PROTOCOLSUdpUDP datagram-only plugins

Required Exports

Every plugin file must export three functions at its module root. The build script calls all three for every discovered plugin, so a file missing any of them does not compile.

  • create_plugin builds the plugin. Config is passed in as a raw &serde_json::Value; returning Err marks the config invalid, and the plugin’s failure_policy decides what happens next.
  • failure_policy says what happens when construction fails: FailClosed rejects startup or reload, KeepLastKnownGood keeps serving the previous plugin cache on reload (startup still rejects), and OptionalFailOpen logs the failure and omits the plugin. Only non-enforcing plugins such as best-effort telemetry may use OptionalFailOpen.
  • config_contract lists example configs that together reach every nested object the plugin reads. The repository’s plugin test sweep validates each example without a Tokio runtime (construction must neither need one nor spawn Tokio tasks) and checks that an unknown key injected into any closed object is rejected. Declare maps of operator-chosen names with with_free_form_objects and embedded foreign documents, such as a JSON Schema, with with_opaque_documents.
rust
pub fn create_plugin(
    config: &Value,
    _http_client: PluginHttpClient,
) -> Result<Option<Arc<dyn Plugin>>, String> {
    Ok(Some(Arc::new(MyPlugin::new(config)?)))
}

pub fn failure_policy() -> crate::plugins::PluginFailurePolicy {
    crate::plugins::PluginFailurePolicy::KeepLastKnownGood
}

pub fn config_contract() -> crate::plugins::PluginConfigContract {
    crate::plugins::PluginConfigContract::closed(vec![
        serde_json::json!({}),
        serde_json::json!({ "header_value": "ferrum-custom" }),
    ])
}

Use with_free_form_objects(&[...]) on the contract for operator-named maps such as header maps, and with_opaque_documents(&[...]) for embedded documents such as a JSON Schema.

Full Example: Header Injection Plugin

Adds a configurable X-Custom-Gateway header to every proxied request and echoes it back in the response. The repository ships two complete examples under custom_plugins/examples/: example_plugin.rs (headers, request body, protocol and correlation capabilities) and example_audit_plugin.rs (database-backed audit log with migrations). They compile only when listed, for example FERRUM_CUSTOM_PLUGINS=example_plugin.

rust — custom_plugins/my_plugin.rs
use async_trait::async_trait;
use http::HeaderValue;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

use crate::plugins::{Plugin, PluginHttpClient, PluginResult, RequestContext, ResponseBodyProduction, TransactionSummary};

pub struct MyPlugin {
    header_value: String,
}

impl MyPlugin {
    pub fn new(config: &Value) -> Result<Self, String> {
        let object = config.as_object().ok_or("config must be an object")?;
        if object.keys().any(|key| key != "header_value") {
            return Err("unknown configuration field".into());
        }
        let value = match object.get("header_value") {
            None => "ferrum-custom",
            Some(Value::String(value)) => value,
            Some(_) => return Err("header_value must be a string".into()),
        };
        if value.len() > 8192 {
            return Err("header_value exceeds 8192 bytes".into());
        }
        HeaderValue::from_str(value).map_err(|_| "invalid header value")?;
        Ok(Self { header_value: value.to_string() })
    }
}

#[async_trait]
impl Plugin for MyPlugin {
    fn name(&self) -> &str {
        "my_plugin"
    }

    fn priority(&self) -> u16 {
        // Default band — runs after transforms, before logging.
        super::super::plugins::priority::DEFAULT
    }

    fn response_body_production(&self) -> ResponseBodyProduction {
        ResponseBodyProduction::Never
    }

    fn modifies_request_headers(&self) -> bool {
        true
    }

    async fn on_request_received(&self, _ctx: &mut RequestContext) -> PluginResult {
        PluginResult::Continue
    }

    async fn before_proxy(
        &self,
        _ctx: &mut RequestContext,
        headers: &mut HashMap<String, String>,
    ) -> PluginResult {
        headers.insert("x-custom-gateway".to_string(), self.header_value.clone());
        PluginResult::Continue
    }

    async fn after_proxy(
        &self,
        _ctx: &mut RequestContext,
        _response_status: u16,
        response_headers: &mut HashMap<String, String>,
    ) -> PluginResult {
        response_headers.insert("x-custom-gateway".to_string(), self.header_value.clone());
        PluginResult::Continue
    }

    async fn log(&self, _summary: &TransactionSummary) {
        // Awaited in order; buffered responses wait for it. Hand the summary to a
        // bounded channel drained by a plugin-owned worker instead of doing I/O here.
    }
}

/// Factory function — called by the build-script-generated registry.
pub fn create_plugin(
    config: &Value,
    _http_client: PluginHttpClient,
) -> Result<Option<Arc<dyn Plugin>>, String> {
    Ok(Some(Arc::new(MyPlugin::new(config)?)))
}

/// Required: how a construction failure affects plugin-cache publication.
pub fn failure_policy() -> crate::plugins::PluginFailurePolicy {
    crate::plugins::PluginFailurePolicy::KeepLastKnownGood
}

/// Required: example configs for the plugin test sweep. This config is flat,
/// so the root object is the only one the sweep injects an unknown key into.
pub fn config_contract() -> crate::plugins::PluginConfigContract {
    crate::plugins::PluginConfigContract::closed(vec![
        serde_json::json!({}),
        serde_json::json!({ "header_value": "my-gateway" }),
    ])
}

Database Migrations

Plugins that need their own tables can declare migrations via plugin_migrations(). The build script discovers them, and they run after core gateway migrations, under the same migration lock, when FERRUM_MODE=migrate FERRUM_MIGRATE_ACTION=up is executed. They are tracked per plugin in _ferrum_plugin_migrations, so plugin version numbers never collide with core versions. Plugin migrations are SQL-only (SQLite, PostgreSQL, MySQL) and are skipped on MongoDB.

ℹ️
Prefix your table names with your plugin name (e.g. my_plugin_) to avoid collisions with core tables or other plugins. Plugin migrations have no automatic down path; removing a plugin leaves its tables in place.
rust — plugin_migrations() example
use crate::config::migrations::CustomPluginMigration;

pub fn plugin_migrations() -> Vec<CustomPluginMigration> {
    vec![CustomPluginMigration {
        version: 1,
        name: "create_audit_log",
        checksum: "v1_create_audit_log_example",
        sql: "CREATE TABLE IF NOT EXISTS my_plugin_audit_log (id VARCHAR(255) PRIMARY KEY, message TEXT NOT NULL)",
        sql_postgres: None,
        sql_mysql: None,
    }]
}

Running migrations

bash
# Apply pending core and plugin migrations
FERRUM_MODE=migrate FERRUM_MIGRATE_ACTION=up \
  FERRUM_DB_TYPE=sqlite FERRUM_DB_URL="sqlite://ferrum.db?mode=rwc" \
  cargo run -- run

# Preview, or report status, without applying
FERRUM_MODE=migrate FERRUM_MIGRATE_ACTION=up FERRUM_MIGRATE_DRY_RUN=true \
  FERRUM_DB_TYPE=sqlite FERRUM_DB_URL="sqlite://ferrum.db?mode=rwc" \
  cargo run -- run
FERRUM_MODE=migrate FERRUM_MIGRATE_ACTION=status \
  FERRUM_DB_TYPE=sqlite FERRUM_DB_URL="sqlite://ferrum.db?mode=rwc" \
  cargo run -- run

Versions must be unique, increasing, and within 1..=2147483647. Applied migrations are checksum-verified, so never edit one after it ships; add a new version instead.

Build-time Filtering

Set FERRUM_CUSTOM_PLUGINS at build time to include only specific plugins. If unset, every .rs file directly in custom_plugins/ is compiled in. The examples under custom_plugins/examples/ are never compiled by default, and published binaries and images leave the variable unset, so they contain no example plugins.

bash
FERRUM_CUSTOM_PLUGINS=my_plugin,audit_plugin cargo build --release

Best Practices

Validate config in new()

Return Err(String) for missing required fields, invalid values, wrong JSON types, and unknown keys at every depth. Admission and ferrum-edge validate call the constructor, so keep it free of side effects and stage background workers in start_background_tasks().

Use serde_json::Value

Config arrives as a raw &serde_json::Value. Use .as_str(), .as_bool(), .as_u64() etc., or deserialize into a typed struct with serde_json::from_value.

Declare modifies_request_headers

Return true only when the plugin actually changes request headers. This lets the gateway skip cloning the header map for plugins that don't need to modify it.

Avoid panics

Never unwrap() or panic!() in production plugin code. Use Result types and propagate errors via PluginResult. Release builds use panic = "abort", so a panic in a plugin terminates the whole gateway process.

Architecture Overview → Browse Built-in Plugins