Authors: Anjali Kushwaha and Rohit Singh
The procedures below must be followed in order to publish customized policies for Anypoint Flex Gateway using Rust:
- Create Policy Definition Files.
- Create the JSON Schema File.
- Create the Definition Metadata YAML File.
- Create Metadata YAML File (Implementation).
- Create the Implementation Binary Files.
- Publish Policy Definition Asset to Exchange.
- Add Policy Implementation File to the Published Policy Definition.
- Apply the Policy from Anypoint API Manager to an API.
Prerequisites
- Anypoint Platform with Administrator Access.
- GitHub Access.
- Rust must be Installed on the System (Download from here if not already https://www.rust-lang.org/tools/install).
- Flex Gateway created on Anypoint Platform.
Create Policy Definition Files
In order to upload the policy implementation, it is essential to generate a policy definition file in both JSON and YAML formats.
The API Manager utilizes these files to obtain essential data for rendering the user interface and metadata related to the policy implementation.
- The JSON file contains the JSON schema language to define the policy’s interface.
- The YAML file includes details such as the policy’s category, interface scope, necessary attributes, and RAML/OAS snippets.
- These files can be generated locally or replicated from custom policy definition samples.
Create the JSON Schema File
The interface for the policy is defined in the JSON schema file, which outlines the required and supported properties needed to configure it. Additionally, the file provides annotations to further refine the type of each property enabling certain fields to carry out specialized functions within the Anypoint platform such as the secure handling of secrets or Dataweave validations.
The JSON schema file should contain the following fields:
- Top-level @context
Commonly-used names can be security or config.
security and config aliases values:- Security: anypoint://vocabulary/policy.yaml#
- Config: anypoint://vocabulary/policyConfigurationsForUI.yaml#
- Top-level title
- $schema which is a link to the JSON Schema specification.
- Root type of object
- Top-level description
- Each property must also include:
- Title
Used by API Manager UI to provide the field name. - Description
Used by API Manager UI to give the description of the field. - Type
Supported primitive types are integer, string, object, boolean, and array.
- Title
Each property can include the following:
- Format
Options are dataweaveExpression and ipRange. - Default
It allows the user to enter a default value which is provided in the UI. - @context with a @characteristics array.
The following options are used to filter the type with more annotations:- config:commaSeparatedValues
The values will result in an array. - security:sensitive It checks whether the property is masked while entering in UI or not.
- config:commaSeparatedValues
The following code is an example of a Custom Auth Header JSON schema:
{
"title": "Custom Auth Header",
"type": "object",
"description": "Enforces HTTP authentication matching x-custom-auth value to what is configured in the policy.",
"properties": {
"secret-value": {
"title": "Custom Auth Header Password",
"type": "string",
"@context": {
"@characteristics": [
"security:sensitive"
]
}
}
},
"required": [
"secret-value"
],
"unevaluatedProperties": false,
"@context": {
"@vocab": "anypoint://vocabulary/policy.yaml#",
"security": "anypoint://vocabulary/policy.yaml#"
},
"$id": "custom-auth-header-simple",
"$schema": "https://json-schema.org/draft/2019-09/schema"
}
Create the Definition Metadata YAML File
The policy and its requirements are detailed in the YAML file. The YAML file is not bound to any specific runtime or binary.
The Definition YAML file should contain the following fields:
- Header
#%Policy Definition 0.1. - Name
Policy name that will be displayed in the UI of API Manager. It should be a string. - Description
It should be a string. - Category
Specifies the category related to the policy. For e.g., security, compliance, troubleshooting, and transformation. - Provided Characteristics
A list is used to specify the features the policy provides. It should be an array of strings. Use providedCharacteristics: [] in case of empty.
The following code is an example of a Custom Auth Header definition YAML file:
#%Policy Definition 0.1
name: Custom Auth Header
description: Enforces Custom Auth Header according to the details configured in the policy.
category: Security
providedCharacteristics:
- Requires authentication
requiredCharacteristics: []
interfaceScope: ["api", "resource"]
interfaceTransformation: []
encryptionSupported: true
violationCategory: authentication
Create Metadata YAML File (Implementation)
Information on how the policy description has been specifically implemented is provided in the metadata YAML file. There may be several implementations of the same policy specification. Each one is a separate Exchange asset or a different version of the same Exchange asset.
The Implementation YAML file should contain the following fields:
- Header
#%Policy Implementation 1.0 - Technology
flexGateway. - Name
Name of your implementation. - minRuntimeVersion
1.0.0 onwards. - Release notes.
The following code is an example of a Custom Auth Header Implementation YAML file:
#%Policy Implementation 1.0
minRuntimeVersion: 1.0.0
technology: flexGateway
name: Custom Auth Header Implementation
releaseNotes: Initial version
Create the Implementation Binary Files
A JAR file for Mule 4 policies or a WASM file for Anypoint Flex Gateway serves as the implementation binary file. These files must function as described by the definition metadata and support all configuration fields.
- Create the Rust project via the following command in cmd: cargo new flex_custom_policy_auth_header –lib
- This creates a flex_custom_policy_auth_header directory. Below shows the files/folders that automatically get generated within the directory.

Copy the following into Cargo.toml, located in the flex_custom_policy_auth_header directory:
[package]
name = "flex_custom_policy_auth_header"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
name="flex_custom_policy_auth_header"
path="src/lib.rs"
[dependencies]
proxy-wasm = { git = "https://github.com/proxy-wasm/proxy-wasm-rust-sdk.git", tag = "v0.2.0" }
serde = {version="1.0",features=["derive"]}
serde_json = "1.0"
log = "0.4"
Add the policy bootstrapping code in the RUST library(src/lib.rs) as described below:

use proxy_wasm::traits::*;
use proxy_wasm::types::*;
use log::info;
use serde::{Deserialize, Serialize};
proxy_wasm::main! {{
proxy_wasm::set_log_level(LogLevel::Trace);
proxy_wasm::set_root_context(|_| -> Box<dyn RootContext> {
Box::new(HttpConfigHeaderRoot {
secret: String::new()
})
});
}}
struct HttpConfigHeader {
secret: String
}
impl Context for HttpConfigHeader {}
impl HttpContext for HttpConfigHeader {
fn on_http_request_headers(&mut self, _num_headers: usize, _end_of_stream: bool) -> Action {
info!("on_http_request_headers");
if let Some(value) = self.get_http_request_header("x-custom-auth") {
if self.secret == value {
info!("on_http_request_headers allowing");
return Action::Continue;
}
}
info!("on_http_request_headers blocking");
self.send_http_response(401, Vec::new(), None);
Action::Pause
}
fn on_http_request_body(&mut self, _body_size: usize, _end_of_stream: bool) ->Action{
info!("on_http_request_body");
Action::Continue
}
fn on_http_response_headers(&mut self, _num_headers: usize, _end_of_stream: bool)->Action{
info!("on_http_response_headers");
Action::Continue
}
fn on_http_response_body(&mut self, _body_size: usize, _end_of_stream: bool) -> Action {
info!("on_http_response_body");
Action::Continue
}
}
#[derive(Serialize, Deserialize)]
struct PolicyConfig {
#[serde(alias = "secret-value")]
secret_value: String
}
struct HttpConfigHeaderRoot {
secret: String
}
impl Context for HttpConfigHeaderRoot {}
impl RootContext for HttpConfigHeaderRoot {
fn on_configure(&mut self,_:usize)->bool{
if let Some(config_bytes) = self.get_plugin_configuration() {
let config:PolicyConfig = serde_json::from_slice(config_bytes.as_slice()).unwrap();
self.secret = config.secret_value;
info!("secret header is {}",self.secret);
}
true
}
fn create_http_context(&self, _: u32) -> Option<Box<dyn HttpContext>> {
Some(Box::new(HttpConfigHeader {
secret: self.secret.clone(),
}))
}
fn get_type(&self) -> Option<ContextType> {
Some(ContextType::HttpContext)
}
}
Add wasm32 as a target to enable compilation, for that we’ve to run the below command from the main directory itself using cmd:
rustup target add wasm32-unknown-unknown
Use the command below to compile your custom policy. After running this command from the main directory, a target folder will be created:
cargo build –target wasm32-unknown-unknown –release

- Use the following command from your main directory to install wasm-gc and enable optimization:
cargo install wasm-gc
- Executing wasm-gc against your binary will optimize it:
wasm-gc target/wasm32-unknown-unknown/release/flex_custom_policy_auth_header.wasm -o target/flex_custom_policy_auth_header-final.wasm
Note: The Implementation Metadata YAML, Definition Metadata YAML & JSON Schema File can be placed anywhere in the directory. This process of Binary file creation is irrespective of these files.
Publish Policy Definition Asset to Exchange
Publish the policy definition asset to Exchange after creating the necessary JSON and YAML policy definition files.
- Open MuleSoft Exchange and click on Publish new asset.
- Enter the name Custom Auth Header.
- Select Policy as Asset Type.
- Upload the file schema.json.
- Upload the file definition.yaml.
- Click on Publish.

Note: The name of the asset should be the same that we have given in the Yaml definition file which we have uploaded as definition.yaml.
Add Policy Implementation File to the Published Policy Definition
A binary file and a metadata file are needed to implement the policy and make it accessible during runtime. The metadata file specifies which runtime version and which technology the binary file is applicable to. A YAML file must contain the metadata. The policy logic and runtime execution are managed by the binary file. The file may be a JAR file for Mule 4 runtime or a WebAssembly (WASM) file for Anypoint Flex Gateway.
- Click on Implementations and Add Implementation.
- Enter the name Custom Auth Header Impl.
- Upload the file flex_custom_policy_auth_header.wasm you obtained in previous steps after compiling the sources using Rust and Cargo.
- Upload the file implementation.yaml.
- Click on Add Implementation.


Apply the Policy from Anypoint API Manager to an API
Once that policy is published in Exchange, it will be ready to be applied to APIs. Follow these steps:
- Publish an API Spec in Exchange.
- Define in API Manager a new API in the previously created API Flex Gateway.
- Make sure to add the Implementation URI of some existing deployed API for which you want to make requests through Flex Gateway.
- Apply in that API instance the policy – defining any text as value – and wait some minutes until it is applied.
- Make a call to the API using Postman. It should produce a 401 error.
- Repeat the call, but pass a new header named x-custom-auth with the value you have defined in the policy. The API should produce an HTTP 200 status.
