We are going to design a WebAssembly (Wasm) plugin sandbox with the following features:
- Permissions: The sandbox should control what resources a plugin can access.
- ABI: A stable application binary interface for plugins to interact with the host.
- Versioning: Support for multiple versions of the plugin interface.
- Registry: A system to manage available plugins, their versions, and dependencies.
We'll break down the system into components:
- Plugin Loader: Loads Wasm modules and instantiates them with the appropriate imports.
- Permission System: Defines and enforces permissions (e.g., filesystem, network, etc.).
- ABI: Defines the set of functions that the host provides to the plugin and vice versa.
- Versioning: Handles different versions of the plugin interface (maybe through a version negotiation).
- Registry: A storage (could be in-memory or on-disk) for plugin metadata, binaries, and dependencies.
Let's design each part:
A. ABI:
We define a set of host functions that the plugin can call. We also define the plugin's exported functions that the host can call.
Example host functions (for the plugin):
- log: for logging
- read_file: with permission check
- write_file: with permission check
- http_request: with permission check and allowed domains
The plugin must export a function named "plugin_main" (or similar) that the host will call to start the plugin.
We also need to define a way for the plugin to report errors and to exit.
We'll have an ABI version number. The host will pass its ABI version when instantiating the plugin, and the plugin can choose to support that version or not.
How to handle ABI versioning?
Option 1: The host and plugin agree on an ABI version during instantiation. The host provides the ABI version in the import object (as a constant). The plugin checks and if incompatible, it can refuse to start.
Option 2: We have multiple sets of import objects, one for each ABI version. The plugin specifies which ABI version it was built for in its metadata. The host then uses the corresponding import object.
We'll go with option 2 because it's more explicit and easier to manage.
The plugin metadata (in the registry) will include the required ABI version.
B. Permission System:
We'll define a set of permissions (as a bitmask or a set of strings). The plugin's manifest (metadata) declares the permissions it requires. The host, when installing or running the plugin, can grant or deny these permissions.
During instantiation, we create an import object that only includes the host functions that the plugin is allowed to use. Alternatively, we can include all functions but have them check permissions internally.
We'll do the latter for flexibility: the host functions will check the plugin's granted permissions and if an operation is not allowed, they will return an error.
But note: if we include all functions, the plugin can try to call any function. We might want to not even provide the functions that are not granted. However, for ABI stability, we might want to always provide the same set of functions (for a given ABI version) and let the functions themselves check.
Alternatively, we can have two layers:
- The host only provides the functions that are granted. But then the ABI must be defined such that the absence of a function means it's not granted. This might break if the plugin expects a function to be there.
So we'll provide all functions in the ABI, but each function will check the permission. If the permission is not granted, the function returns an error (or traps).
We'll define a permission for each host function (or group of functions). For example:
- permission "file_read" for read_file
- permission "file_write" for write_file
- permission "network" for http_request
The plugin's manifest will list the permissions it requires. The user (or system) must grant these permissions.
C. Registry:
We need to store plugins and their metadata. The registry should support:
- Listing available plugins
- Installing a plugin (from a Wasm binary or a package)
- Uninstalling
- Enabling/disabling
- Managing versions (multiple versions of the same plugin)
The registry can be a simple in-memory map or a more persistent storage. For simplicity, let's assume an in-memory registry for now.
Each plugin in the registry will have:
- name
- version
- abi_version (the ABI version it was built for)
- permissions (the set of permissions it requires)
- wasm_bytes (or a path to the wasm file)
- dependencies (list of other plugins it depends on, with version constraints)
We also need to handle dependencies. The registry should be able to resolve dependencies and ensure that the required plugins are installed and enabled.
D. Plugin Loader:
The loader will:
1. Look up the plugin in the registry by name and version (or latest).
2. Check if the required ABI version is supported by the host.
3. Check if the required permissions are granted (we can have a system for the user to grant permissions at install time or at runtime).
4. Resolve dependencies: load and instantiate required plugins first, and pass their exports to the current plugin (if they are meant to be used as libraries).
5. Instantiate the Wasm module with the import object that includes:
- The host functions (with permission checks)
- The exports of the dependent plugins (if any)
6. Call the plugin's main function (or let the host decide when to call it).
We must consider that dependencies are also plugins that might have their own dependencies.
We'll need to avoid circular dependencies and handle version constraints.
E. Host Environment:
The host will provide the ABI functions. We'll design the ABI functions to be safe and to check permissions.
We'll also need to define how the plugin can call back into the host (for example, to schedule a task, or to emit events). This will be part of the ABI.
Implementation Steps:
-
Define the ABI:
We'll have a set of host functions that the plugin can import. We'll also define the plugin's exports.
Let's assume we are using WebAssembly Text Format (WAT) for clarity, but we'll design in Rust-like pseudocode.
Host imports (for the plugin):
(module
(import "host" "log" (func $log (param i32 i32))) ; log a string (pointer and length)
(import "host" "read_file" (func $read_file (param i32 i32 i32) (result i32))) ; (path_ptr, path_len, buf_ptr) -> result (0 on success, error code otherwise)
(import "host" "write_file" (func $write_file (param i32 i32 i32 i32) (result i32))) ; (path_ptr, path_len, buf_ptr, buf_len) -> result
(import "host" "http_request" (func $http_request (param i32 i32 i32 i32) (result i32))) ; (url_ptr, url_len, method_ptr, method_len) -> request_id (0 on error)
... etc.
)
The plugin must export:
(export "plugin_main" (func $plugin_main))
Additionally, the plugin might export other functions that the host can call (for example, to handle events). We'll define a standard set of optional exports.
-
Define the metadata format for a plugin:
We can use a custom section in the Wasm binary, or a separate manifest file. Let's use a custom section named "plugin_metadata".
The metadata could be JSON:
{
"name": "example_plugin",
"version": "1.0.0",
"abi_version": 1,
"permissions": ["file_read", "file_write", "network"],
"dependencies": [
{ "name": "logger", "version": "1.0" }
]
}
-
Registry:
We'll have a struct:
struct PluginInfo {
name: String,
version: String,
abi_version: u32,
permissions: Vec<Permission>,
dependencies: Vec<Dependency>,
wasm_bytes: Vec<u8>,
}
struct Dependency {
name: String,
version_req: VersionReq, // using semver
}
enum Permission {
FileRead,
FileWrite,
Network,
// ... etc.
}
-
Loading and instantiation:
Steps:
a. Load the plugin's Wasm bytes and parse the metadata (from custom section).
b. Check if the host supports the abi_version (the host has a set of supported ABI versions, maybe an array of versions it knows).
c. Check if the required permissions are granted. We'll assume that at install time, the user grants the permissions. So the registry stores the granted permissions for each plugin installation.
d. Resolve dependencies: for each dependency, find a plugin in the registry that matches the name and version constraint and is enabled. If not found, error.
e. Build the import object for the plugin:
- For each dependency, we need to pass its exports. But note: the dependency might have been instantiated already? We don't want to instantiate the same plugin multiple times.
We can have a plugin instance cache. When a plugin is first instantiated (as a dependency), we store its exports. Then when another plugin depends on it, we can pass the same instance? But note: each plugin instance has its own memory. We cannot share memory between plugins unless we explicitly design for it.
Alternatively, we can instantiate each plugin only once and then use the same instance for all dependents. But then the plugin must be designed to be a singleton. Also, the plugin might have state that is shared? We might want to allow multiple instances of the same plugin?
Let's think: if plugin A and plugin B both depend on plugin C, should they share the same instance of C? That would mean C's state is shared, which might be intended (like a shared logger) or not.
We can leave it to the plugin author: if the plugin is designed to be a singleton, then we instantiate it once and reuse. If it is designed to be instantiated multiple times, then we instantiate a new one for each dependent.
But how do we know? We can have a flag in the metadata: "singleton": true/false.
Alternatively, we can always instantiate a new one for each dependent, and let the host provide a way to get the singleton instance? That might be complex.
Let's go with: by default, we instantiate a new instance for each dependent. But if the plugin is marked as a singleton, then we instantiate it once and reuse.
So in the registry, we store for each plugin:
- The Wasm bytes
- The metadata
- For singleton plugins: we store the instance (once instantiated) and its exports.
But note: the same plugin (same name and version) might be required by multiple other plugins. We want to avoid instantiating it multiple times if it's a singleton.
Steps for dependency resolution:
For each dependency D:
- Look up the plugin info for D (name and version constraint) in the registry. If not found, error.
- If D is marked as singleton and already instantiated, use the existing instance.
- Else, instantiate D (recursively resolving its dependencies) and if it's singleton, store the instance for future use.
We must be careful with circular dependencies.
System Architecture
┌─────────────────────────────────────────────────────────────┐
│ Plugin Registry │
│ • Plugin metadata storage │
│ • Version resolution │
│ • Dependency management │
│ • ABI compatibility matrix │
└───────────────┬─────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Permission Manager │
│ • Capability-based permissions │
│ • Resource quotas │
│ • Dynamic permission grants/revokes │
│ • Permission inheritance from dependencies │
└───────────────┬─────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ ABI Compatibility Layer │
│ • Version negotiation │
│ • Function signature adaptation │
│ • Memory layout translation │
│ • Interface stubs/proxies │
└───────────────┬─────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Wasm Runtime Sandbox │
│ • Multiple runtime instances │
│ • Isolated memory spaces │
│ • Controlled imports/exports │
│ • Trap handling & recovery │
└─────────────────────────────────────────────────────────────┘
1. Plugin Metadata & Registry
Plugin Manifest (JSON Schema)
{
"$schema": "https://wasm-plugin.org/schema/manifest/v1",
"name": "com.example.image-processor",
"version": "1.2.3",
"abi_version": "2.1.0",
"description": "Image processing plugin",
"author": "Example Corp",
"license": "MIT",
"entrypoint": "plugin_main",
"capabilities": [
"file-read:/tmp/*",
"file-write:/tmp/output/",
"network:https://api.example.com/*",
"cpu:1000", // milliseconds per call
"memory:64MB"
],
"dependencies": [
{
"name": "com.example.image-lib",
"version": "^1.0.0",
"optional": false
}
],
"exports": {
"functions": [
{
"name": "process_image",
"signature": "(i32, i32, i32) -> i32", // (input_ptr, input_len, options_ptr) -> result
"http": "/v1/process"
}
],
"events": ["image_processed", "error"]
},
"wasm": {
"file": "plugin.wasm",
"sha256": "a1b2c3...",
"compile_target": "wasm32-wasip1"
}
}
Registry Implementation (Rust)
use semver::Version;
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone)]
pub struct PluginManifest {
pub id: PluginId,
pub version: Version,
pub abi_version: Version,
pub capabilities: Vec<Capability>,
pub dependencies: Vec<Dependency>,
pub exports: ExportSpec,
pub wasm_hash: String,
pub entrypoint: String,
}
#[derive(Debug, Clone)]
pub struct Registry {
plugins: HashMap<PluginId, HashMap<Version, PluginManifest>>,
// Reverse index: capability -> plugins that have it
capability_index: HashMap<Capability, HashSet<PluginId>>,
// ABI compatibility matrix
abi_matrix: AbiCompatibilityMatrix,
}
impl Registry {
pub fn register(&mut self, manifest: PluginManifest) -> Result<(), RegistryError> {
// Validate manifest
self.validate(&manifest)?;
// Check ABI compatibility with host
if !self.abi_matrix.is_compatible(&manifest.abi_version) {
return Err(RegistryError::IncompatibleAbi);
}
// Check dependency constraints
self.check_dependencies(&manifest)?;
// Store in registry
self.plugins
.entry(manifest.id.clone())
.or_insert_with(HashMap::new)
.insert(manifest.version.clone(), manifest);
// Update capability index
for cap in &manifest.capabilities {
self.capability_index
.entry(cap.clone())
.or_insert_with(HashSet::new)
.insert(manifest.id.clone());
}
Ok(())
}
pub fn resolve(
&self,
id: &PluginId,
constraints: &VersionConstraints,
) -> Option<PluginManifest> {
self.plugins.get(id)?.values()
.filter(|m| constraints.matches(&m.version))
.max_by_key(|m| m.version)
.cloned()
}
}
2. ABI System
ABI Definition (WIT - WebAssembly Interface Type)
package wasm:plugin;
// Core ABI - must be implemented by all plugins
interface plugin {
// Lifecycle
init: func() -> result<error>;
start: func() -> result<error>;
stop: func() -> result<error>;
dispose: func();
// Configuration
configure: func(config: json) -> result<json, error>;
get-metadata: func() -> metadata;
// Main functionality (plugin-specific, defined in exports)
// ...
}
// Host capabilities available to plugins
interface host {
// Logging
log: func(level: log-level, message: string);
// File system (sandboxed)
fs-read: func(path: string) -> result<list<u8>, error>;
fs-write: func(path: string, data: list<u8>) -> result<u64, error>;
// Network
http-request: func(
url: string,
method: http-method,
headers: list<tuple<string, string>>,
body: option<list<u8>>
) -> result<http-response, error>;
// Time
monotonic-clock: func() -> u64;
// Random
random-bytes: func(len: u32) -> list<u8>;
}
// Error type
variant error {
permission-denied(string),
resource-quota-exceeded(string),
invalid-argument(string),
not-found(string),
internal(string),
abi-mismatch(string),
dependency-failed(string),
}
// Metadata structure
record metadata {
name: string,
version: string,
abi-version: string,
capabilities: list<string>,
dependencies: list<dependency>,
}
record dependency {
name: string,
version: string,
required: bool,
}
ABI Compatibility Matrix
#[derive(Debug, Clone)]
pub struct AbiCompatibilityMatrix {
// Maps (host_abi, plugin_abi) -> compatibility level
matrix: HashMap<(Version, Version), CompatibilityLevel>,
// Default fallback strategy
fallback_policy: FallbackPolicy,
}
#[derive(Debug, Clone, PartialEq)]
pub enum CompatibilityLevel {
Full, // Directly compatible
Shadowed, // Plugin uses subset of host features
Adaptable, // Needs runtime adaptation
Incompatible,
}
impl AbiCompatibilityMatrix {
pub fn check(&self, host_abi: &Version, plugin_abi: &Version) -> CompatibilityLevel {
// Check exact match first
if let Some(level) = self.matrix.get(&(host_abi.clone(), plugin_abi.clone())) {
return level.clone();
}
// Check version ranges
for ((h, p), level) in &self.matrix {
if host_abi.major == h.major &&
plugin_abi.major == p.major &&
plugin_abi.minor >= p.minor {
return level.clone();
}
}
CompatibilityLevel::Incompatible
}
}
3. Permission System
Capability-Based Permissions
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum Capability {
// File system
FileRead { pattern: PathPattern },
FileWrite { pattern: PathPattern },
FileDelete { pattern: PathPattern },
// Network
Network {
domains: Vec<DomainPattern>,
ports: Vec<PortRange>,
},
// System
SpawnProcess,
EnvironmentAccess(Vec<String>),
// Resource quotas
Cpu { milliseconds: u64 },
Memory { bytes: u64 },
Instances { count: u32 },
// Plugin-specific
Custom(String),
}
#[derive(Debug, Clone)]
pub enum PathPattern {
Exact(PathBuf),
Prefix(PathBuf),
Glob(String),
}
#[derive(Debug, Clone)]
pub struct PermissionGrant {
pub plugin_id: PluginId,
pub capabilities: Vec<Capability>,
pub granted_by: String,
pub expires_at: Option<DateTime<Utc>>,
pub conditions: Vec<PermissionCondition>,
}
pub struct PermissionManager {
grants: HashMap<PluginId, PermissionGrant>,
// Effective permissions after combining with dependencies
effective: HashMap<PluginId, Vec<Capability>>,
}
impl PermissionManager {
pub fn check(&self, plugin_id: &PluginId, required: &Capability) -> Result<(), PermissionError> {
let effective = self.effective.get(plugin_id)
.ok_or_else(|| PermissionError::NoPermissions(plugin_id.clone()))?;
if effective.contains(required) {
Ok(())
} else {
Err(PermissionError::CapabilityMissing(
plugin_id.clone(),
required.clone()
))
}
}
// Inherit permissions from dependencies
pub fn inherit_from_dependencies(
&mut self,
plugin_id: &PluginId,
dependencies: &[PluginId],
) -> Result<(), PermissionError> {
let mut inherited = HashSet::new();
for dep in dependencies {
if let Some(dep_perms) = self.effective.get(dep) {
// Only inherit if dependency has the same or stricter pattern
for cap in dep_perms {
if self.can_inherit(cap) {
inherited.insert(cap.clone());
}
}
}
}
// Merge with direct permissions
if let Some(direct) = self.effective.get_mut(plugin_id) {
direct.extend(inherited);
}
Ok(())
}
}
4. Sandbox Runtime
Sandbox Instance
pub struct WasmSandbox {
instance: Instance,
memory: Memory,
store: Store<SandboxContext>,
permissions: Vec<Capability>,
abi_version: Version,
resource_limits: ResourceLimits,
}
#[derive(Clone)]
pub struct SandboxContext {
pub plugin_id: PluginId,
pub permissions: Vec<Capability>,
pub resource_usage: ResourceUsage,
pub parent_chain: Vec<PluginId>, // For dependency hierarchy
pub logger: Logger,
}
impl WasmSandbox {
pub fn new(
wasm_bytes: Vec<u8>,
manifest: &PluginManifest,
permissions: Vec<Capability>,
dependencies: Vec<WasmSandbox>,
abi_adapter: &dyn AbiAdapter,
) -> Result<Self, SandboxError> {
// Create store with context
let context = SandboxContext {
plugin_id: manifest.id.clone(),
permissions: permissions.clone(),
resource_usage: ResourceUsage::default(),
parent_chain: Vec::new(),
logger: Logger::new(&manifest.id),
};
let mut store = Store::new(&Engine::default(), context);
// Apply resource limits
apply_limits(&mut store, &manifest.capabilities)?;
// Build import object with ABI adaptation
let imports = abi_adapter.build_imports(
&manifest.abi_version,
&permissions,
&dependencies,
)?;
// Instantiate module
let module = Module::new(&store.engine(), &wasm_bytes)?;
let instance = Instance::new(&mut store, &module, &imports)?;
// Get memory
let memory = instance
.get_memory(&store, "memory")
.ok_or(SandboxError::MissingMemory)?
.clone();
Ok(Self {
instance,
memory,
store,
permissions,
abi_version: manifest.abi_version.clone(),
resource_limits: extract_limits(&manifest.capabilities),
})
}
pub fn call(&mut self, func: &str, params: &[Val]) -> Result<Vec<Val>, CallError> {
// Check resource quota before call
self.check_cpu_quota()?;
let func = self.instance.get_func(&self.store, func)
.ok_or_else(|| CallError::FunctionNotFound(func.to_string()))?;
// Adapt parameters if needed
let adapted_params = self.adapt_params(func, params)?;
// Call with trap handling
match func.call(&mut self.store, &adapted_params) {
Ok(results) => {
self.record_cpu_usage()?;
Ok(results)
}
Err(trap) => {
self.handle_trap(trap)?;
Err(CallError::Trap(trap.to_string()))
}
}
}
}
5. Plugin Loader
pub struct PluginLoader {
registry: Arc<Registry>,
permission_mgr: Arc<PermissionManager>,
runtime: WasmRuntime,
abi_adapters: HashMap<Version, Box<dyn AbiAdapter>>,
}
impl PluginLoader {
pub async fn load(
&self,
plugin_id: PluginId,
version_constraint: &VersionConstraint,
config: PluginConfig,
) -> Result<PluginHandle, LoadError> {
// 1. Resolve plugin from registry
let manifest = self.registry.resolve(&plugin_id, version_constraint)
.ok_or_else(|| LoadError::PluginNotFound(plugin_id.clone()))?;
// 2. Check permissions
let granted_perms = self.permission_mgr.get_granted(&plugin_id)
.ok_or_else(|| LoadError::NoPermissions(plugin_id.clone()))?;
// 3. Resolve dependencies
let dependency_manifests = self.resolve_dependencies(&manifest)?;
let dependency_sandboxes = self.load_dependencies(&dependency_manifests).await?;
// 4. Get ABI adapter
let abi_adapter = self.abi_adapters.get(&manifest.abi_version)
.ok_or_else(|| LoadError::UnsupportedAbi(manifest.abi_version.clone()))?;
// 5. Create sandbox
let wasm_bytes = self.registry.get_wasm(&plugin_id, &manifest.version)?;
let sandbox = WasmSandbox::new(
wasm_bytes,
&manifest,
granted_perms.clone(),
dependency_sandboxes,
abi_adapter.as_ref(),
)?;
// 6. Initialize plugin
let handle = PluginHandle::new(
plugin_id,
manifest.version.clone(),
sandbox,
dependency_manifests,
config,
);
// 7. Call init
handle.init().await?;
Ok(handle)
}
async fn load_dependencies(
&self,
manifests: &[PluginManifest],
) -> Result<Vec<WasmSandbox>, LoadError> {
let mut sandboxes = Vec::new();
for dep in manifests {
// Recursively load dependencies
let dep_sandbox = self.load(
dep.id.clone(),
&VersionConstraint::Exact(dep.version.clone()),
PluginConfig::default(),
).await?;
sandboxes.push(dep_sandbox.into_inner());
}
Ok(sandboxes)
}
}
6. Versioning Strategy
Semantic Versioning with ABI Stability
Major.Minor.Patch
ABI Stability Rules:
1. Major version change: Incompatible ABI change
2. Minor version change: Backward-compatible additions
3. Patch version change: Bug fixes only
Compatibility Matrix:
Host\Plugin 1.0.x 1.1.x 2.0.x
1.0.x ✓ ✗ ✗
1.1.x ✗ ✓ ✗ (Shadow mode: adapts 1.1 to 1.0)
2.0.x ✗ ✗ ✓
Version Resolver
pub struct VersionResolver {
// Constraints: (plugin_id, version_range) -> candidate versions
available_versions: HashMap<PluginId, Vec<Version>>,
abi_compatibility: AbiMatrix,
}
impl VersionResolver {
pub fn resolve(
&self,
requirements: &[DependencyRequirement],
host_abi: &Version,
) -> Result<HashMap<PluginId, Version>, ResolutionError> {
let mut solution = HashMap::new();
let mut worklist = Vec::from(requirements);
while let Some(req) = worklist.pop() {
// Skip if already resolved
if solution.contains_key(&req.id) {
continue;
}
// Find compatible versions
let candidates = self.find_candidates(&req.id, &req.version_req)?
.into_iter()
.filter(|v| self.abi_compatibility.check(host_abi, v).is_compatible())
.collect::<Vec<_>>();
if candidates.is_empty() {
return Err(ResolutionError::NoCompatibleVersion(req.id, req.version_req));
}
// Pick highest compatible version
let selected = candidates.iter().max().unwrap();
solution.insert(req.id.clone(), selected.clone());
// Get dependencies of selected version
let manifest = self.get_manifest(&req.id, selected)?;
worklist.extend(manifest.dependencies.iter().map(|d| DependencyRequirement {
id: d.name.clone(),
version_req: d.version_req.clone(),
}));
}
Ok(solution)
}
}
7. Complete Implementation Example
// main.rs - Plugin Sandbox Manager
use wasm_plugin_sandbox::{Registry, PluginLoader, PermissionManager};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize components
let mut registry = Registry::new();
let permission_mgr = PermissionManager::new();
let loader = PluginLoader::new(registry.clone(), permission_mgr.clone());
// Register plugins
registry.register(parse_manifest("plugins/image-processor/manifest.json")).await?;
registry.register(parse_manifest("plugins/image-lib/manifest.json")).await?;
// Grant permissions to plugin
permission_mgr.grant(PermissionGrant {
plugin_id: "com.example.image-processor".parse()?,
capabilities: vec![
Capability::FileRead { pattern: PathPattern::Prefix("/tmp/".into()) },
Capability::Network {
domains: vec![DomainPattern::Exact("api.example.com".into())],
ports: vec![PortRange::Single(443)],
},
Capability::Cpu { milliseconds: 5000 },
],
granted_by: "admin".into(),
expires_at: None,
conditions: vec![],
})?;
// Load plugin
let handle = loader.load(
"com.example.image-processor".parse()?,
&VersionConstraint::Carets("1.0".parse()?),
PluginConfig::default(),
).await?;
// Call plugin function
let result = handle.call(
"process_image",
&[Val::I32(input_ptr), Val::I32(input_len), Val::I32(options_ptr)],
).await?;
println!("Plugin returned: {:?}", result);
// Cleanup
handle.stop().await?;
Ok(())
}
8. Security Considerations
-
Attack Surface Reduction:
- Only allow required imports
- Validate all exported functions
- Sandbox memory access
-
Resource Limits:
struct ResourceLimits {
max_memory: Option<u64>,
max_cpu_time: Duration,
max_instructions: Option<u64>,
max_instances: u32,
}
-
Isolation:
- Each plugin in separate memory space
- No shared memory unless explicitly allowed
- Capability-based security (no ambient authority)
-
Supply Chain Security:
- Verify plugin signatures
- Check integrity with hashes
- Audit registry entries
9. Deployment & Operation
Registry Server (HTTP API)
GET /api/v1/plugins
POST /api/v1/plugins (with manifest + wasm)
GET /api/v1/plugins/{id}/versions
GET /api/v1/plugins/{id}/{version}/manifest
GET /api/v1/plugins/{id}/{version}/wasm
POST /api/v1/permissions/grant
DELETE /api/v1/permissions/{plugin_id}
Configuration Example (YAML)
sandbox:
runtime: wasmtime
max_memory_per_plugin: 256MB
max_cpu_time_per_call: 5s
enable_debug: false
registry:
url: "https://plugins.example.com"
cache_dir: "/var/cache/plugins"
verify_signatures: true
permissions:
default_deny: true
auto_grant_for_system: false
abi:
supported_versions: ["1.0.0", "2.0.0", "2.1.0"]
default_version: "2.1.0"
adaptation_strategy: "shadow" # or "reject"
10. Testing Strategy
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_permission_enforcement() {
let registry = Registry::new();
let perm_mgr = PermissionManager::new();
let loader = PluginLoader::new(registry, perm_mgr);
// Plugin tries to read unauthorized file
let result = loader.load_with_config(
"malicious.plugin",
PluginConfig {
permissions: vec![
Capability::FileRead {
pattern: PathPattern::Exact("/tmp/allowed.txt".into())
}
],
..Default::default()
},
).await;
assert!(matches!(result, Err(LoadError::PermissionDenied(_))));
}
#[test]
fn test_abi_compatibility() {
let matrix = AbiCompatibilityMatrix::new();
assert!(matrix.check(&"1.0.0".parse().unwrap(), &"1.2.0".parse().unwrap()).is_compatible());
assert!(!matrix.check(&"2.0.0".parse().unwrap(), &"1.0.0".parse().unwrap()).is_compatible());
}
}
Key Design Decisions
- Capability-based permissions instead of traditional UNIX-style permissions
- Explicit ABI versioning with compatibility matrix
- Dependency isolation - each plugin gets its own sandbox
- Registry as source of truth for plugin metadata and versions
- Graceful degradation - plugins can declare optional capabilities
- Resource quotas enforced at runtime
- Version constraint resolution using semver ranges
This design provides a production-ready Wasm plugin system with enterprise-grade security, version management, and dependency resolution. The system is modular enough to swap out components (different Wasm runtimes, different registry backends) while maintaining the core security model.