Plan a WebAssembly plugin sandbox negotiating capability tokens, version skew, and…
- User
Plan a WebAssembly plugin sandbox negotiating capability tokens, version skew, and memory ceilings.
- Assistant
Plan a WebAssembly plugin sandbox negotiating capability tokens, version skew, and memory ceilings.
We are planning a WebAssembly (Wasm) plugin sandbox that negotiates capability tokens, version skew, and memory ceilings. The goal is to design a system where:
Steps:
Capability Tokens:
Version Skew:
Memory Ceiling:
Implementation Plan:
We can model the negotiation as a handshake between the host and the plugin.
Steps in the handshake:
a. The host loads the Wasm module (but doesn't instantiate it yet) and reads the custom sections (or a specific section) that contain: - The plugin's required capabilities (as a list of capability IDs) - The plugin's supported version range (min and max) - The plugin's minimum memory requirement (in pages)
b. The host then decides: - Which capabilities to grant (based on policy and the plugin's request). The host may also have a set of default granted capabilities. - The host's own supported version range for the interface. - The host's memory ceiling (which must be >= plugin's minimum).
c. The host and plugin then agree on: - The granted capabilities (the intersection of the plugin's request and host's grant policy, but note: host can grant more than requested? Probably not, because plugin only expects what it requests. But host can grant a superset? That might be okay if the plugin doesn't use the extra ones. However, for security, we might want to grant exactly what is needed? But the plugin might have optional capabilities. We can have: - Required: must be granted. - Optional: host can choose to grant or not. So the plugin specifies required and optional capabilities. The host must grant all required, and may grant some optional.
- The agreed version: the highest version in the intersection of [plugin.min, plugin.max] and [host.min, host.max]. If the intersection is empty, fail.
- The memory ceiling: the host sets a ceiling (which is at least the plugin's minimum). The host might set a lower ceiling than the plugin's maximum? But note: the plugin's memory request is a minimum, so the host must set at least that. The host can set a higher ceiling if allowed by policy, but note that the plugin might not use more than its minimum? Actually, the plugin can grow memory up to the ceiling. So the host sets the ceiling, and the plugin can use up to that.
d. The host then instantiates the Wasm module with: - A set of imported functions that correspond to the granted capabilities (each capability is implemented by the host as an import). - The agreed version (maybe passed as a global or an import? Or the host uses the agreed version to decide which set of functions to provide? Actually, the version might determine the shape of the imported functions. So we need to have versioned imports.
e. Alternatively, we can have a two-phase instantiation: Phase 1: The host and plugin exchange their requirements and the host decides on the configuration (capabilities, version, memory). Phase 2: The host instantiates the Wasm module with the configuration.
However, note that the Wasm module must be instantiated with the correct imports. The imports are determined by the capabilities and the version.
How to handle versioned imports?
Option 1: The host provides a set of functions for each version. The plugin expects a specific version's set of functions. Then the agreed version tells the host which set of functions to provide.
Option 2: Use a single set of functions that are backward compatible? But that might not be possible if there are breaking changes.
We can design the host's API to be versioned by having a namespace for each version? But Wasm imports are by module and name. We can have:
(import "host_capabilities" "version_1_function1" ...)
(import "host_capabilities" "version_2_function1" ...)
But that would require the plugin to import by the versioned name? That doesn't sound good because the plugin must be compiled for a specific version and then the host must provide that exact version.
Alternatively, we can have a single import namespace and use the version to decide which function to call? That doesn't work because the plugin's code is compiled against a specific function signature.
So we need to have the plugin import functions that are exactly as expected by the plugin's version. Then the host must provide the same function signatures for that version.
How about:
The plugin, when compiled, is compiled against a specific version of the host API (say version 1.2.3). The plugin's Wasm binary will have imports for that version.
The host, when it sees the plugin's required version (say it requires at least 1.2.0 and at most 2.0.0), and the host supports versions 1.0.0 to 1.5.0, then they agree on version 1.5.0 (the highest common). But note: the plugin was compiled against 1.2.3, so it expects the function signatures of 1.2.3. If 1.5.0 is backward compatible with 1.2.3, then the same imports work. But if there's a breaking change between 1.2.3 and 1.5.0, then the plugin's imports won't match the host's 1.5.0 functions.
Therefore, we must ensure that the host's API is backward compatible within a major version? Or we must recompile the plugin for the agreed version? That's not possible because the plugin is already compiled.
So the host must provide the exact version that the plugin was compiled against? But the plugin might specify a range. How does the plugin know which version it was compiled against? It must embed that in the binary.
Let's change the perspective:
The plugin specifies a required version (the version of the host API it was compiled against). The host must provide that exact version? Or at least a version that is compatible? We need a compatibility policy.
We can define that the host API is backward compatible for minor and patch versions, and breaking changes only in major versions. Then:
Plugin compiled against version X.Y.Z expects the host to provide at least X.Y.Z and less than X+1.0.0.
Then the negotiation:
Plugin says: I require host API version >= X.Y.Z and < X+1.0.0.
Host says: I support host API version >= A.B.C and < D.E.F.
They agree on the highest version that is in the intersection and that is compatible with the plugin's compiled version? Actually, the plugin's compiled version is X.Y.Z, so it expects the host to provide at least X.Y.Z and less than X+1.0.0. So the agreed version must be in [X.Y.Z, X+1.0.0) and also in [A.B.C, D.E.F). The agreed version is the maximum version in the intersection? But note: if the host supports a higher minor version, say X+1.0.0 is not allowed, but X.Y+1.0 might be. So we can agree on the highest version in the intersection that is less than X+1.0.0.
However, if the host only supports up to X.Y+1.0, then that's okay. But if the host supports X+1.0.0 and above, then the intersection might be empty? Actually, the plugin's upper bound is X+1.0.0 (exclusive), so if the host's lower bound is X+1.0.0, then no intersection.
So the host must provide a version that is at least the plugin's required version and less than the next major version of the plugin's required version? That seems restrictive.
Alternatively, we can have the plugin specify a range of versions it is compatible with (maybe because it was compiled against a specific version but we know it works with a range). Then the host and plugin agree on the highest version in the intersection of the two ranges.
But then the host must provide the function signatures for that agreed version. How does the host know which functions to provide for version 1.5.0? The host must implement multiple versions? That's a lot of work.
Alternatively, we can have a single set of functions that are always the same? Then versioning is about the semantics, not the function signatures. Then the version is just a number that both sides agree on, and they use the same set of function signatures. Then the version is used to decide which behavior to use (maybe the functions have version-dependent behavior). But that puts the burden on the function implementations to handle multiple versions.
Given the complexity, let's assume:
The host API is versioned and each version has a set of function signatures. The plugin is compiled against a specific version (say V). The host must provide the exact version V? But then the host must support every version that any plugin might request? That's not scalable.
We need a better way.
Idea: The host provides a single set of functions that are the latest version. The plugin, if it was compiled against an older version, must adapt? That would require the plugin to be recompiled for the latest version? But we want to run old plugins.
Alternatively, we can have the host provide a versioned namespace? For example, the plugin imports from "host_v1" for version 1, and "host_v2" for version 2. Then the host must have both namespaces? That means the host must maintain multiple versions of the API in the same binary? That's possible but complex.
Given the constraints, let's simplify:
We will have a single version of the host API at a time. The host and plugin agree on a version, and the host provides the function signatures for that version. The host must implement all versions that it wants to support? That's not feasible.
Alternatively, we can use a proxy approach: the host provides a single set of functions that are the latest, and then we have a compatibility layer in the plugin? But the plugin is Wasm, so we can't change it.
Given the time, let's assume we are designing for a controlled environment where the host and plugin are developed together and we only have one version at a time? But the requirement says "version skew", so we must handle multiple versions.
Let's look at how other systems handle this:
- In WebAssembly System Interface (WASI), there are multiple versions (like stable, preview1, etc.). The plugin (WASI program) is compiled against a specific version. The host (WASI runtime) must provide that version. But the host typically only supports one version at a time? Actually, WASI has multiple versions and the host can support multiple versions by having different import namespaces? Not exactly.
After research, I recall that WASI uses a versioned module name? Actually, the current WASI uses a fixed set of imports. For multiple versions, they might use different module names? I'm not sure.
Given the complexity, let's change the requirement:
We will not version the function signatures. Instead, we will have a fixed set of capabilities (each capability is a function or a set of functions). Then the versioning is about the semantics of the capabilities? But then we have the same problem: if we change the semantics of a capability, we break old plugins.
So we need to version the capabilities themselves? Or we need to have multiple versions of each capability? That's too heavy.
Alternatively, we can have the host and plugin agree on a version, and then the host provides a set of functions that are exactly as defined in that version. The host must have an implementation for each version it wants to support. This is similar to having multiple versions of an API.
Given the scope, let's assume we are going to support a few versions (maybe 2 or 3) and the host must implement each one. Then the negotiation:
The plugin says: I was compiled against version X (and I might work with versions >=X and <X+1, but let's assume we only support exact version for now).
The host says: I support versions {1, 2, 3}.
They agree on the version that the plugin requires, if the host supports it. Otherwise, fail.
Then the host provides the imports for that version.
Steps:
Plugin custom section:
- required_version: string (e.g., "1.2.3")
- required_capabilities: list of strings (capability IDs)
- optional_capabilities: list of strings
- min_memory: integer (pages)
Host:
- supported_versions: list of strings (e.g., ["1.0.0", "1.1.0", "1.2.0", "2.0.0"])
- capability_grant_policy: a function that takes required and optional capabilities and returns the granted set (must include all required, and may include some optional).
- memory_ceiling: integer (pages) or a policy that sets the ceiling (maybe based on the plugin's min_memory and system conditions).
Negotiation:
version_agreed = plugin.required_version if plugin.required_version in host.supported_versions else fail.
capabilities_granted = host.policy(plugin.required_capabilities, plugin.optional_capabilities)
memory_ceiling_set = max(plugin.min_memory, host.memory_ceiling) but note: host.memory_ceiling might be a fixed value or a function. We can let the host set a ceiling that is at least the plugin's min.
Then instantiate the Wasm module with:
- memory: with the agreed memory ceiling (the host sets the maximum memory for the module, which is the ceiling).
- imports: the host provides functions for each granted capability, using the function signatures of the agreed version.
How does the host know which function signatures to provide for a given version? We need a mapping from version to a set of function signatures (or an interface definition).
We can have an interface definition language (IDL) for each version? Or we can have a Rust trait for each version? But the host might be implemented in any language.
Given the complexity of versioning, let's assume we are only going to support one version for now, and then extend later.
But the requirement says version skew, so we must design for multiple versions.
Let's simplify the versioning:
We will have a major version that breaks compatibility. Minor versions are backward compatible.
The plugin is compiled against a specific minor version (say 1.2) of the major version 1.
The host supports major version 1, and a set of minor versions.
The host and plugin agree on the highest minor version that the host supports and that is >= the plugin's required minor version.
Then, the function signatures for minor versions are the same? Actually, if minor versions are backward compatible, then the function signatures are the same. So the host can provide the same set of functions for all minor versions of the same major version? But what if a minor version adds new capabilities? Then the plugin that was compiled against an older minor version might not expect the new capabilities? But if the plugin doesn't use them, it's okay. However, the plugin's import section must exactly match the host's provided imports. So if the host provides more imports (for new capabilities) than the plugin expects, that's okay because the plugin doesn't import them. But if the plugin expects a capability that was added in a later minor version, then the host must provide it.
Wait, the capabilities are negotiated separately. So the version is about the core API (maybe the set of fundamental functions that are always present) and the capabilities are optional.
Let's separate:
- The core API: a set of functions that are always imported by the plugin (like the "host" module). These are versioned and breaking changes only in major versions.
- The capabilities: optional functions that the plugin can import if granted. These are identified by capability IDs and are not versioned? Or they are versioned within the core API version?
We can say:
For a given major version of the core API, the set of capabilities is fixed? Or the capabilities can evolve independently? If they evolve, then we need to version the capabilities too.
Given the time, let's define:
The core API is versioned (major.minor). The core API includes:
- A function to query the granted capabilities (so the plugin can check what it has).
- Maybe some core functions (like memory management?).
The capabilities are separate and are identified by strings. The host provides a function for each granted capability. The function signatures for capabilities are not versioned? But then if we change a capability's signature, we break old plugins.
So we must version the capabilities as well? That becomes too complex.
Alternative: The capabilities are just tokens (integers) that the plugin can use to call host functions? But then the host must provide a generic invocation function? That's how some plugin systems work.
Let's consider a different design:
The host provides a single function: `invoke(capability_id: u32, args: ...) -> ...`. Then the capability_id determines what operation to perform. The plugin doesn't import individual capabilities, but uses this single function. Then the versioning is only about the core API (which might include this invoke function and maybe some other core functions). The capabilities are just numbers, and the host maps them to actual functions.
But then the plugin must know the capability_ids for the operations it wants. These capability_ids are defined by the host? And the host and plugin must agree on the meaning of each capability_id? That's similar to having a fixed set of capabilities.
We can have:
The core API (versioned) defines a set of standard capabilities (with fixed IDs) and their signatures. The host must implement these standard capabilities. Then the plugin can request these standard capabilities.
Additionally, the host can define custom capabilities (with host-specific IDs) and the plugin must know about them? That would break portability.
Given the complexity, let's stick to:
The core API is versioned (major.minor). The core API includes:
- A function to get the list of granted capabilities (maybe by name or ID).
- A function to invoke a capability by ID (if we go the generic route) OR
- The host provides individual functions for each granted capability, and the plugin must import them by name? But then the import names must be known.
How about:
The plugin declares a list of required capabilities by name (e.g., "fs.read", "net.connect"). The host, when granting a capability, provides an import with a fixed name for that capability? But then if we have multiple versions of the same capability (different signatures) we have a problem.
Let's assume that each capability has a fixed signature that never changes. Then the host and plugin agree on the capability by name, and the host provides a function with a fixed signature for that capability. Then the versioning is only about the core API (which might include the way to query capabilities and invoke them?).
We can have:
Core API (versioned) provides:
- `list_capabilities() -> []string` (the list of granted capabilities by name)
- `get_capability(name: string) -> externref` (or a function pointer? but Wasm doesn't have function pointers in the standard). Alternatively, we can have the host provide a separate import for each granted capability, and the plugin uses the `list_capabilities` to know which ones are available? But then the plugin must import all possible capabilities? That's not dynamic.
Alternatively, the host provides a single function invoke(capability_name: string, ...) but then we lose type safety.
Given the constraints of WebAssembly, the common pattern is to have the host provide a set of functions as imports. So the plugin must know the exact function names and signatures to import.
Therefore, we must have:
The plugin, when compiled, knows the exact set of functions it wants to import (by module and name). The host must provide those exact functions.
Then the capability negotiation is about which of the plugin's required functions the host is willing to provide? But the plugin's required functions are fixed by the code. So the plugin must declare a set of functions it wants to import, and the host must provide them. That's not flexible.
We need a way for the plugin to declare "I need the function with signature X for capability Y", but the host might have multiple versions of the same capability? That's getting too complex.
Given the time, I propose a simpler design:
We will have a fixed set of capabilities, each with a fixed function signature. The plugin declares which of these fixed capabilities it requires. The host grants a subset (must include all required). Then the host provides the functions for the granted capabilities.
The versioning is only about the core API (which might be a small set of functions, say `host_version` and `host_capabilities`). The core API is versioned and the plugin must import the core API functions of the agreed version.
The capabilities are not versioned? But then if we change the signature of a capability, we break old plugins. So we must version the capabilities too? Or we must never change the signature of a capability.
We can have:
The core API version determines the set of available capabilities and their signatures. So if we change a capability's signature, we create a new core API version.
Then:
The plugin declares:
- required core API version (the version it was compiled against)
- required capabilities (by name, but the names and signatures are defined by the core API version)
The host supports a set of core API versions.
They agree on a core API version (the highest that the plugin requires and the host supports, and that is compatible? Actually, the plugin requires a specific version? Or a range? Let's say the plugin requires exactly version X, because it was compiled against X).
Then the host provides the core API functions for version X (if supported) and the capabilities that are defined in version X (and that the plugin requested and the host granted).
This way, the capabilities are tied to the core API version.
Steps:
Plugin custom section:
core_api_version: string (required, exact version)
required_capabilities: list of strings (capability names as defined in that core_api_version)
optional_capabilities: list of strings
min_memory: integer
Host:
supported_core_api_versions: list of strings (exact versions it supports)
capability_grant_policy: for a given core_api_version, it decides which capabilities to grant (from the plugin's request). But note: the set of available capabilities might depend on the core_api_version? Yes, because different versions might have different capabilities.
Negotiation:
If plugin.core_api_version not in host.supported_core_api_versions -> fail.
Let available_capabilities = the set of capabilities defined in core_api_version (we have an IDL for each version).
Then the plugin's required and optional capabilities must be subsets of available_capabilities? Otherwise, fail.
Then granted_capabilities = host.policy(plugin.required_capabilities, plugin.optional_capabilities) for that version.
Then the host provides:
- The core API imports for the agreed core_api_version (a fixed set of functions for that version).
- For each granted capability, the host provides the function as defined in the core_api_version for that capability.
Memory: the host sets a memory ceiling that is at least plugin.min_memory.
This design ties capabilities to the core API version, so changing a capability's signature means a new core API version.
Now, how does the host know the function signatures for each core API version? We need to define an IDL for each version.
Example:
Core API version 1.0.0:
Core functions:
- host_version() -> (major: u32, minor: u32, patch: u32)
- host_capabilities() -> (list of strings)
Capabilities:
- "fs.read": (fd: u32, buffer: pointer, length: u32) -> (result: u32)
- "net.connect": (host: pointer, port: u16) -> (result: u32)
Core API version 1.1.0 might add a new capability or change an existing one? But if we change an existing one, then it's a new version.
This design is similar to having an interface that is versioned, and each version defines a set of functions.
Implementation:
The host must have an implementation for each supported core API version.
The plugin must be compiled against a specific core API version.
The custom section in the Wasm binary must contain:
- core_api_version (string)
- required_capabilities (list of strings)
- optional_capabilities (list of strings)
- min_memory (u32)
The host reads this custom section and then:
1. Check if the core_api_version is supported.
2. Check that the required and optional capabilities are defined in that version.
3. Run the grant policy to get the granted capabilities.
4. Set the memory ceiling (at least min_memory).
5. Instantiate the Wasm module with:
- The core API imports for the agreed version (the host provides the functions for that version).
- The capability imports for the granted capabilities (the host provides the functions for those capabilities, as defined in the agreed version).
How does the host provide the core API imports? They are fixed for the version. The host must have a mapping from (version, function_name) to a host function.
We can have:
For each supported core API version, we have a struct or a table of functions.
Example in Rust (pseudocode):
struct CoreApiV1_0_0 {
host_version: fn() -> (u32, u32, u32),
host_capabilities: fn() -> Vec<String>,
}
Then when instantiating for version 1.0.0, we provide the imports from an instance of CoreApiV1_0_0.
Similarly for capabilities:
struct CapabilitiesV1_0_0 {
fs_read: fn(fd: u32, buffer: u32, length: u32) -> u32,
net_connect: fn(host: u32, port: u16) -> u32,
}
But note: the host might not implement all capabilities for a version? Actually, the set of capabilities for a version is fixed. The host may choose not to grant some capabilities, but then the plugin must not import them. So the host only provides the granted capabilities.
How does the plugin import? The plugin's Wasm binary will have imports for the core API functions and for the capabilities it requires (and maybe optional ones that it conditionally uses?).
The plugin must import exactly the core API functions and the capabilities it requires (and optionally, the host might provide extra capabilities that the plugin doesn't import? that's okay).
So during instantiation, the host must provide:
- The core API functions (exactly the set defined by the version).
- The granted capabilities (exactly the set that the plugin will import? Actually, the plugin will import the capabilities it requires, and the host must provide those. The host might grant more, but the plugin doesn't import them, so they are not provided? That's okay.
But note: the plugin's import section will have a fixed set of imports. The host must provide exactly those imports? Or can the host provide more? In Wasm, the host must provide at least the imports that the module requires. It can provide extra? Actually, the module only imports what it uses. The host can provide more, but the module won't use them. So it's okay.
However, the plugin might conditionally use optional capabilities. How does it know if they are granted? The core API function host_capabilities returns the list of granted capabilities. So the plugin can check if a capability is granted before using it.
So the plugin should not import optional capabilities? Instead, it should use the host_capabilities to check and then use a dynamic invocation? But we don't have dynamic invocation in Wasm.
Wait, we have two options:
Option A: The plugin imports all capabilities (required and optional) as separate functions. Then if the host doesn't grant an optional capability, the instantiation fails because the import is missing.
Option B: The plugin does not import optional capabilities. Instead, it uses a generic `invoke_capability` function that takes a capability name and arguments? Then the host provides a single `invoke_capability` function that dispatches based on the name.
Option B allows dynamic capability usage and doesn't require the plugin to import every possible capability. But then we lose type safety because the arguments and return types are not checked by the Wasm type system.
Given that we are in a sandbox and we want type safety, Option A is better. But then the plugin must know which capabilities it might use and import them all. And the host must grant them all (at least the required ones) for the plugin to run.
So:
The plugin must import every capability it might use (required and optional). The host must grant all required capabilities, and may grant some optional ones. But if the plugin imports an optional capability and the host doesn't grant it, then instantiation fails.
To avoid that, the plugin should only import required capabilities. Then how does it use optional ones? It can't.
Therefore, we must have:
Required capabilities: the plugin must have them to function. The host must grant them.
Optional capabilities: the plugin may use them if granted. But if the plugin imports them, then the host must grant them or instantiation fails.
So the plugin must not import optional capabilities? Then how does it use them? We need a dynamic way.
Given the trade-offs, I choose Option B:
The core API provides:
- `host_version()`
- `host_capabilities() -> list of strings`
- `invoke_capability(capability_name: string, arg0: i32, arg1: i32, ...) -> i32` (but we need a way to pass arbitrary arguments? We can use a linear memory approach: the plugin passes a pointer to a buffer and a length, and the host reads the arguments from memory? That's how WASI does it.)
But then we lose the type safety of Wasm function signatures.
Alternatively, we can have the core API provide a function for each capability? That's Option A.
Given the requirement for version skew and capabilities, I think we need to go with Option A and have the core API version define a fixed set of functions (core + capabilities). Then the plugin must import exactly the functions it uses. The host must provide them if granted.
Then the plugin's required capabilities are the ones it imports (excluding the core API functions). The host must grant all imported capabilities? Actually, the plugin only imports the capabilities it uses. So the plugin's required capabilities are the ones it imports. The optional capabilities are not imported, so they are not used.
So the negotiation:
The plugin declares a set of required capabilities (the ones it imports). The host must grant all of them.
The host may also grant additional capabilities that the plugin doesn't import? That's okay, but the plugin won't use them.
The plugin can then use the core API function `host_capabilities` to see what was granted, but since it only imports the ones it requires, it doesn't need to check? Actually, if the host grants more, the plugin might not know about them because it didn't import them.
So we don't need optional capabilities in the plugin's declaration? The plugin only declares the capabilities it imports (which are the required ones). The host can grant more, but the plugin can't use them because it doesn't have the function import.
Therefore, the plugin's custom section only needs:
core_api_version: string
required_capabilities: list of strings (the ones it imports)
min_memory: u32
And the host:
supported_core_api_versions: list of strings
capability_grant_policy: given a list of required capabilities (and maybe the core_api_version), returns a set that must include all required capabilities (and may include more). But note: the host can only grant capabilities that are defined in the core_api_version.
Steps:
Read plugin's custom section.
Check core_api_version is supported.
Let available_capabilities = the set of capabilities defined in core_api_version.
Check that required_capabilities is a subset of available_capabilities.
granted_capabilities = host.policy(required_capabilities, core_api_version) // must include all required_capabilities.
Then the host provides:
- Core API functions for core_api_version.
- For each capability in required_capabilities (and maybe also for any extra granted capabilities? But the plugin doesn't import them, so we don't need to provide them) the host provides the function.
But note: the plugin's import section will have imports for the core API and for the required capabilities. So the host must provide exactly those.
The host may grant extra capabilities, but the plugin doesn't import them, so they are not provided. That's okay.
Memory ceiling: host sets at least min_memory.
This design seems workable.
Now, how do we represent the custom section in the Wasm binary?
We can define a custom section with a name, say "plugin_metadata".
The section data can be in a simple format:
core_api_version: length prefixed string
required_capabilities: vector of length prefixed strings
min_memory: u32
Example (in binary):
section "plugin_metadata" {
// core_api_version
len: 5
data: "1.0.0"
// required_capabilities count: 2
count: 2
// first capability: "fs.read"
len: 6
data: "fs.read"
// second: "net.connect"
len: 10
data: "net.connect"
// min_memory: 10 (pages)
min_memory: 10
}
The host reads this section and then proceeds with negotiation.
Summary:
Steps for the host:
1. Read the Wasm binary and parse the custom section "plugin_metadata".
2. Extract core_api_version, required_capabilities, min_memory.
3. Check if core_api_version is in supported_core_api_versions. If not, fail.
4. Look up the set of capabilities defined for core_api_version (from the host's IDL for that version). Let's call it available_capabilities.
5. Check that required_capabilities is a subset of available_capabilities. If not, fail.
6. Run the capability_grant_policy for this core_api_version and the required_capabilities. The policy must return a set that includes all required_capabilities. Let granted_capabilities = policy_result.
7. Set memory_ceiling = max(min_memory, host_memory_ceiling_policy()).
8. Instantiate the Wasm module with:
- memory: with maximum memory = memory_ceiling.
- imports:
* core_api_imports: the set of functions for core_api_version (from the host's IDL for that version).
* capability_imports: for each capability in required_capabilities (and note: the plugin only imports required_capabilities, so we only need to provide those) the function from the host's IDL for that capability in core_api_version.
Note: The host's IDL for a core_api_version defines: - The core functions (with their signatures and implementation). - The capabilities (with their signatures and implementation).
The host must have an implementation for every core function and every capability in every supported core_api_version? Yes, because a plugin might request any capability in that version.
This design requires the host to maintain multiple versions of the core API and capabilities. That's a maintenance burden but allows versioning.
If we don't want to maintain multiple versions, we can only support one version and require plugins to be compiled against that version. But the requirement says "version skew", so we must support multiple versions.
Given the complexity, we might start with one version and then extend.
Let's write the plan in steps:
Phase 1: Define the core API version 1.0.0 and its capabilities.
Phase 2: Implement the host to support version 1.0.0 and the custom section parsing.
Phase 3: Implement the negotiation and instantiation.
Phase 4: Extend to support multiple versions by having an IDL for each version and a way to select the correct one.
Given the time, I'll outline the code structure for the host:
struct CoreApiVersion {
version: String,
core_functions: HashMap<String, Function Sig>, // map from function name to signature (and implementation)
capabilities: HashMap<String, Function Sig>, // map from capability name to signature (and implementation)
}
The host has a list of supported CoreApiVersion.
When a plugin comes in:
let metadata = parse_custom_section(&wasm_bytes, "plugin_metadata");
let plugin_version = metadata.core_api_version;
let required_caps = metadata.required_capabilities;
let min_memory = metadata.min_memory;
let supported_version = host.supported_versions.iter()
.find(|v| v.version == plugin_version)
.ok_or("Unsupported version")?;
// Check required_caps are in supported_version.capabilities
for cap in &required_caps {
if !supported_version.capabilities.contains_key(cap) {
return Err(format!("Capability {} not available in version {}", cap, plugin_version));
}
}
let granted_caps = host.capability_grant_policy.grant(&required_caps, &plugin_version)?;
// granted_caps must include all required_caps
let memory_ceiling = max(min_memory, host.memory_ceiling);
// Now, build the imports for instantiation:
let mut imports = Imports::new();
// Add core functions for this version
for (name, func) in &supported_version.core_functions {
imports.insert(name, func); // func must be a host function that matches the signature.
}
// Add granted capabilities (only the required ones? Actually, the plugin will only import the required ones, so we only need to provide those. But what if the host granted more? The plugin doesn't import them, so we don't need to provide them.
for cap in &required_caps {
if let Some(func) = supported_version.capabilities.get(cap) {
imports.insert(cap, func);
}
}
// Then instantiate the module with these imports and memory ceiling.
Note: the plugin must import the core functions and the required capabilities with the exact names as in the version's IDL.
This design requires the plugin to be compiled against the same core API version and the same function names and signatures.
It's a bit rigid but clear.
Let's write the custom section format more formally:
Custom section name: "plugin_metadata"
Data:
u32: length of core_api_version string
bytes: core_api_version string (UTF-8)
u32: number of required capabilities (N)
for i in 0..N:
u32: length of capability name string
bytes: capability name string (UTF-8)
u32: min_memory (in pages)
We'll assume the required capabilities are the ones that the plugin imports (and are not core functions). The core functions are fixed by the version and the plugin must import them all? Or the plugin only imports the core functions it uses? The core API version defines a set of core functions that are always available? Then the plugin must import all of them? Or the host provides all core functions and the plugin can import any subset? But then the versioning of core functions: if we have multiple core functions and we change one, we break old plugins that use that function? So we must version the entire set.
Actually, the core API version defines the entire set of core functions and capabilities. The plugin must import exactly the core functions and capabilities it uses. But the version must be compatible: if the plugin uses a core function that changed signature in a new version, then the version must be different.
So the core API version is tied to the function signatures of all core functions and capabilities.
Therefore, the host must provide the core functions and capabilities exactly as defined in the version.
The plugin must import the core functions it uses and the capabilities it uses. The host will provide them if the version matches and the capabilities are granted.
The plugin's required capabilities (in the metadata) should be the capabilities it imports (and are not core functions). The core functions are not listed in the required capabilities because they are part of the core API.
So the metadata only lists the non-core capabilities that the plugin requires.
Then, during instantiation, the host provides:
- All core functions for the version (even if the plugin doesn't import them? Actually, the plugin will only import the ones it uses. The host must provide exactly the imports that the plugin requires. So the host must look at the plugin's import section to see which core functions and which capabilities are imported.
Wait, we are reading the custom section for required capabilities, but the plugin's import section might import more? Actually, the plugin's import section is fixed. The custom section is a separate declaration. We must ensure that the required_capabilities in the custom section matches the capabilities imported by the plugin (excluding core functions). And the core functions imported by the plugin must be a subset of the core functions defined in the version.
So the host must:
- Parse the Wasm binary to get the import section (before instantiation). This is possible because the Wasm binary has the imports listed.
- Then, from the import section, we can see which modules and names are imported.
- We assume that all imports from the module "core" are core functions? Or we have a convention: the core API is imported from a module named "core" and capabilities from a module named "capabilities"? Or we don't use modules and just use the names? But Wasm imports are by module and name.
We need to define:
The core API functions are imported from module "core".
The capabilities are imported from module "capabilities".
Then:
The plugin's import section will have imports from "core" and "capabilities".
The custom section's required_capabilities are the names of the imports from "capabilities".
The host must check that for each import from "core", the function name and signature match one of the core functions in the agreed version.
And for each import from "capabilities", the function name must be in the granted_capabilities and match the signature for that capability in the agreed version.
Then the host can build the imports object by providing the functions for the core and capabilities that are imported.
So the steps become:
1. Parse custom section to get core_api_version, required_capabilities (from "capabilities" imports), min_memory.
2. Parse the Wasm import section to get the list of imports from "core" and "capabilities".
3. Check that the core_api_version is supported.
4. Check that every import from "core" is defined in the core functions of that version, and that the signature matches.
5. Check that every import from "capabilities" is in the required_capabilities (from custom section) and that the name is in the capabilities of the version and the signature matches.
6. Run the grant policy on the required_capabilities (which are the capabilities imported). The policy must grant all of them.
7. Set memory ceiling.
8. Build the imports:
- For each core import: provide the core function from the version.
- For each capabilities import: provide the capability function from the version (only if granted, but we already granted all required, so they are granted).
This ensures that the plugin only imports the capabilities it requires and that the host grants them.
Now, what about optional capabilities? If the plugin doesn't import an optional capability, then it's not in the required_capabilities and the host doesn't need to grant it. The plugin can check the list of granted capabilities (via a core function) and then conditionally use a capability? But it can't because it didn't import it. So optional capabilities must be imported? Then they become required. So we don't have optional capabilities in this design. The plugin must import every capability it might use, and the host must grant them all.
If we want optional capabilities, we need a dynamic invocation mechanism (Option B). But we already decided against it for type safety.
So we stick to: the plugin imports every capability it uses, and the host must grant them all. There is no optional capability.
Then the required_capabilities in the custom section are exactly the capabilities that the plugin imports from the "capabilities" module.
The custom section is redundant? We can just parse the import section to get the required capabilities. But the custom section also has the core_api_version and min_memory. So we still need it.
We can have:
The custom section provides:
core_api_version
min_memory
And the required capabilities are taken from the import section (from the "capabilities" module).
Then the host doesn't need the custom section to list required capabilities? But then the host doesn't know which capabilities are required until parsing the import section. That's okay.
But the custom section might be easier to parse than the entire Wasm binary? Actually, we need to parse the Wasm binary anyway to get the import section.
We can skip the required_capabilities in the custom section and just use the import section.
However, the custom section might be used to declare the required capabilities for the host's policy before looking at the import section? But the policy can be run after parsing the import section.
Let's change:
Custom section:
core_api_version: string
min_memory: u32
Then, after parsing the Wasm binary, we get the import section and extract:
core_imports: imports from module "core"
capability_imports: imports from module "capabilities"
Then the required capabilities are the names of the capability_imports.
This simplifies the custom section.
Steps:
1. Parse custom section for core_api_version and min_memory.
2. Parse Wasm binary's import section.
3. Check core_api_version is supported.
4. Check that every core_import (by name) is in the core functions of the version and signature matches.
5. Let required_capabilities = the names of the capability_imports.
6. Check that every required_capability is in the capabilities of the version and signature matches.
7. Run grant policy on required_capabilities. Must grant all.
8. Set memory ceiling.
9. Build imports: for each core_import and capability_import, provide the function from the version's definitions.
This seems clean.
Now, what about the core API version's core functions? The plugin must import exactly the core functions it uses, and the host must provide them. The core API version defines a set of core functions (maybe a fixed set). The plugin can import any subset? But if the plugin uses a core function that is not in the version, then it's an error. And if the version adds a new core function, old plugins won't import it.
So the core API version defines the universe of core functions. The plugin can import any of them.
Similarly for capabilities.
Now, the memory ceiling: the host sets a maximum memory for the module. The plugin's min_memory is the minimum number of pages it needs. The host must set the maximum to at least that. The host can set it higher if allowed.
We can have:
memory_ceiling = max(min_memory, host_policy_memory_ceiling())
The host_policy_memory_ceiling() might be a fixed value or based on system conditions.
Finally, we must consider that the Wasm module might have a memory import? Actually, the Wasm module defines its own memory. The host sets the maximum memory when instantiating? In Wasm, the module can define a memory with an initial and maximum. The host can override the maximum? In the Wasm specification, when instantiating, the host can provide a memory with a maximum, and that becomes the module's memory. Alternatively, the module can define its own memory with a maximum, and the host must respect that? Actually, the host can limit the maximum memory by providing a memory with a lower maximum? But the module might require a certain minimum.
We are reading the min_memory from the custom section. The module might also have a memory section that defines initial and maximum. We must ensure that the host's memory ceiling is at least the module's minimum (from custom section) and also at least the module's initial memory? And the host's ceiling must be at least the module's maximum? Or the host can set a lower maximum? The Wasm specification says: if the module defines a maximum, then the instantiated memory must have at most that maximum. But the host can provide a memory with a lower maximum? Actually, the host can provide a memory with a maximum that is less than or equal to the module's maximum? I think the host can provide a memory with a maximum, and that becomes the module's memory. The module's memory definition is just a request? Not exactly.
Given the complexity, let's assume:
The host sets the memory ceiling by providing a memory import? Or by limiting the module's memory growth? Actually, in the Wasm API, when you instantiate a module, you can provide a Memory object with a maximum. The module's own memory definition might have a maximum, but the host's provided memory overrides it? I think the host can provide a memory that has a maximum, and that becomes the module's memory. The module's memory definition is used if the host doesn't provide one.
So we can:
The host creates a Memory object with:
initial: at least the module's initial memory (from the memory section) and at least the min_memory from custom section.
maximum: the host's memory ceiling (which must be >= initial).
Then, when instantiating, we provide that memory as an import? Actually, the module's memory is defined in the module. We can override it by providing a memory import with the same name? There's a standard way: the module can have a memory, and the host can provide a memory with the same name? I think the module's memory is always there, and the host can set limits when creating the instance.
After checking the Wasm spec: the module can define memories. When instantiating, the host can provide memories to satisfy the imports. But the module's own memories are created by the module. The host can set limits on the module's memories? Not directly.
Given the time, let's not get into the details of Wasm memory. We assume the host can limit the module's memory by setting a maximum on the memory object when creating the instance. In practice, Wasm runtimes allow setting a maximum memory.
We'll assume:
The host reads the module's memory section to get the initial memory and the requested maximum (if any). Then the host sets the actual memory ceiling as:
actual_ceiling = max(module_initial, min_memory_from_custom, host_policy_ceiling)
But note: the module might have a maximum in its memory section. The host must not exceed that? Actually, the host can set a lower maximum? The module might require a certain maximum to function. So we must also respect the module's maximum? But the module's maximum might be higher than the host's ceiling. The host can set a lower ceiling, but then the module might fail if it tries to grow beyond the ceiling.
We'll let the host policy decide the ceiling, but it must be at least the module's initial and the custom section's min_memory. And it must be at most the module's maximum if the module specifies a maximum? Actually, the module's maximum is just a limit that the module sets for itself? The host can override? I think the host can set a lower maximum, but then the module might not be able to grow to its requested maximum.
Given the complexity, we'll assume:
The host sets the memory ceiling to:
max( min_memory_from_custom, host_policy_ceiling() )
and also ensure that it is at least the module's initial memory (from the memory section). And if the module has a maximum, then the host ceiling must be at most that maximum? Actually, the host can set a lower maximum, but then the module might fail when trying to grow. So we should respect the module's maximum as an upper bound? Or the module's maximum is just a hint? The Wasm spec says the module can define a maximum, and the host must not allow the memory to grow beyond that? I think the host must respect the module's maximum.
So:
Let module_initial = from memory section (if absent, default 1 page?).
Let module_maximum = from memory section (if absent, then no maximum?).
Then the host's ceiling must be:
>= max(module_initial, min_memory_from_custom)
<= module_maximum (if module_maximum exists)
And also the host_policy_ceiling must be within that range? Actually, the host_policy_ceiling might be lower than module_initial? Then we use module_initial. Or higher than module_maximum? Then we use module_maximum.
So:
let desired_ceiling = max(min_memory_from_custom, host_policy_ceiling());
let actual_ceiling = clamp(desired_ceiling, module_initial, module_maximum);
But note: the module_initial might be less than min_memory_from_custom? Then we use min_memory_from_custom. And if module_maximum is less than min_memory_from_custom, then fail.
This is getting complicated. We might just set the memory when instantiating and let the Wasm runtime handle it? But we want to enforce the ceiling.
Given the time, I'll leave the memory negotiation as:
The host sets the memory ceiling to:
max(min_memory_from_custom, host_policy_ceiling())
and then when instantiating, the host provides a memory with that ceiling. If the module's memory section has a maximum that is lower than our ceiling, then the instantiation will fail (because the module's memory must have a maximum at least as large as the provided memory's maximum? Actually, the module's memory is created with the provided memory? I'm not sure.
We might need to adjust the module's memory limits? That's not standard.
Given the complexity, let's assume the host uses a Wasm runtime that allows setting a memory ceiling independently of the module's memory definition. For example, in Wasmtime, you can set a memory limit for the instance.
So we'll just set the instance's memory limit to our desired ceiling, and the runtime will enforce it.
Steps for memory:
let memory_ceiling = max(min_memory_from_custom, host_policy_ceiling());
Then, when creating the instance, we set the memory limit to memory_ceiling.
Now, let's write the plan in a structured way.
Final Plan:
Host:
- Maintains a set of supported core API versions, each with:
* core_functions: HashMap<String, Function> (where Function includes signature and implementation)
* capabilities: HashMap<String, Function>
- Has a capability grant policy: Fn(&[String], &str) -> Result<HashSet<String>, Error> (takes the list of required capabilities and the core_api_version, returns the set of granted capabilities, which must include all required).
- Has a memory ceiling policy: Fn() -> u32 (returns the host's desired memory ceiling in pages).
Steps for the host when loading a plugin:
1. Read the Wasm binary.
2. Parse the custom section "plugin_metadata" to get:
core_api_version: String
min_memory: u32
3. Parse the Wasm binary's import section to get:
core_imports: Vec<(module: String, name: String)> where module == "core"
capability_imports: Vec<(module: String, name: String)> where module == "capabilities"
4. Look up the core API version in the host's supported versions. If not found, fail.
5. Let version_data = the supported version.
6. Check that every core_import's name exists in version_data.core_functions and that the function signature matches the one expected by the module? We can't check the signature from the import section? Actually, the import section in Wasm includes the function type (signature). So we can check that the host's function for that name has the same type.
7. Let required_capabilities: HashSet<String> = capability_imports.iter().map(|(_, name)| name).collect()
8. Check that every required_capability exists in version_data.capabilities and that the signature matches.
9. Run the grant policy: granted_capabilities = policy(required_capabilities, core_api_version)? The policy must return a set that includes all required_capabilities. If not, fail.
10. Let memory_ceiling = max(min_memory, host.memory_ceiling_policy())
11. Build the imports for instantiation:
For each core_import (module="core", name):
provide the function from version_data.core_functions.get(&name).unwrap()
For each capability_import (module="capabilities", name):
provide the function from version_data.capabilities.get(&name).unwrap() (only if name is in granted_capabilities? But we already granted all required, so it should be. But we can check.)
12. Create a Memory object with initial pages (from the module's memory section? or at least min_memory) and maximum = memory_ceiling. But we don't want to set the initial too high? Actually, the module might have an initial memory in its memory section. We should respect that? The host can provide a memory that has at least the module's initial and at most the ceiling.
How to create the memory? We can:
let module_memory = parse the memory section of the Wasm module to get the initial and maybe maximum.
Then create a Memory with:
initial: max(module_memory.initial, min_memory) ? Actually, the module might require a certain initial. We should set the initial to the module's initial? But the host can override? I think the host can provide a memory with a different initial? Not sure.
Given the complexity, we might let the runtime handle the memory creation, but set the maximum limit to memory_ceiling.
In Wasmtime, you can set the memory limit for the instance.
So we might not need to create a Memory object explicitly? We can set the memory limit when configuring the instance.
13. Instantiate the Wasm module with the imports and the memory limit.
This plan should work.
Let's note the assumptions:
- The core API functions are imported from module "core".
- The capabilities are imported from module "capabilities".
- The custom section "plugin_metadata" contains core_api_version and min_memory.
- The host must have an implementation for every core function and every capability in every supported version.
- The grant policy must grant all required capabilities (the ones imported by the plugin from "capabilities").
This design allows versioning of the entire API (core + capabilities) and negotiation of capabilities.
We can extend later to have optional capabilities by having the plugin import a function that checks if a capability is granted and then invokes it via a generic function? But that would change the core API.
For now, this is a solid plan.
Let's write the plan in a document.
Note: This is a high-level design. The actual implementation details (like how to parse Wasm binary, how to represent functions, etc.) are omitted.
We should also consider:
- Error handling: what if the plugin's import section has an import from a module other than "core" or "capabilities"? We can ignore? Or fail? Probably fail.
- The core_api_version string format: we'll use semantic versioning (e.g., "1.2.3").
- The host's supported_versions: a list of CoreApiVersion structures, each with a version string and the functions.
- The host must be able to have multiple versions of the same function? For example, the function "host_version" might have the same signature in all versions? But if we change the signature, we need a new version.
- The core API version might also define the memory-related functions? We might have core functions for memory management? But we are using linear memory, so maybe not.
We might also want to have a way for the plugin to query the agreed core API version? We have the host_version function? That could return the version.
Let's define the core functions for version 1.0.0:
- host_version() -> (major: u32, minor: u32, patch: u32)
- host_capabilities() -> (list of strings) // the granted capabilities? Or all capabilities that the host supports? Actually, the host should return the granted capabilities (the ones that are available to the plugin). So the plugin can check if a capability is granted even if it didn't import it? But it can't use it because it didn't import. So maybe this function is not needed if we only have required capabilities.
Since we are not having optional capabilities, the plugin knows which capabilities it has because it imported them. So we don't need host_capabilities.
But for debugging, maybe we want the plugin to know the granted set? It can be provided by the host_version? Or we can have a core function that returns the granted capabilities? That might be useful.
Let's have:
core function: list_granted_capabilities() -> list of strings
Then the plugin can see what it has.
But note: the plugin already knows because it imported them. However, if we later add optional capabilities, it would be useful.
We'll include it.
So core functions for 1.0.0:
- host_version() -> (u32, u32, u32)
- list_granted_capabilities() -> vec<str>
And maybe a function to invoke a capability by name? That would be for optional capabilities. We don't have that now.
We'll stick to the design.
Now, write the plan as a document.
Due to the complexity, I'll write a summary.
Summary:
We design a Wasm plugin system with:
1. Custom section "plugin_metadata" containing:
- core_api_version (string)
- min_memory (u32)
2. The plugin must import:
- Core functions from module "core"
- Capabilities from module "capabilities"
3. Host supports multiple core API versions, each defining:
- A set of core functions (with signatures and implementations)
- A set of capabilities (with signatures and implementations)
4. Negotiation steps:
a. Read core_api_version from custom section.
b. Check host supports that version.
c. Parse import section and verify:
- Every import from "core" is a core function in the version and signature matches.
- Every import from "capabilities" is a capability in the version and signature matches.
d. The required capabilities are the names of the imports from "capabilities".
e. Run the grant policy on the required capabilities. Must grant all.
f. Set memory ceiling = max(min_memory, host_memory_ceiling_policy()).
g. Instantiate with:
- Imports: for each core import and each capability import, provide the function from the version's definitions.
- Memory: set maximum to memory_ceiling.
5. The host must implement the grant policy and memory ceiling policy.
This design allows versioning (by having multiple core API versions) and capability negotiation (by granting only the required capabilities).
Future work:
- Add optional capabilities by having a generic invoke function and making capabilities not imported but looked up by name.
- Allow the host to grant more capabilities than required, but the plugin would need a way to discover and use them (via list_granted_capabilities and a generic invoke).
But for now, this is a solid plan.
Let me know if you have any questions. I'll outline a comprehensive design for a WebAssembly plugin sandbox with negotiated capabilities, version skew handling, and memory constraints.
┌─────────────────┐ Negotiation ┌─────────────────┐
│ Plugin │◄──────────────────►│ Host │
│ (Wasm Module) │ │ Sandbox │
└─────────────────┘ └─────────────────┘
│ │
│ 1. Capability Tokens │ 1. Policy Engine
│ 2. Version Proposal │ 2. Resource Manager
│ 3. Memory Requirements │ 3. Version Registry
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ WasmEngine │ │ Capability │
│ (Runtime) │ │ Store │
└─────────────────┘ └─────────────────┘
// Example token format (JSON-like for readability)
{
"token_id": "cap:fs:read:/tmp/data",
"capability_type": "fs.read",
"resource_mask": "/tmp/data/*",
"constraints": {
"max_file_size": 1048576,
"allowed_patterns": ["*.json", "*.txt"]
},
"expiry": "2024-12-31T23:59:59Z",
"signature": "host-signature-here"
}
sys.time, sys.env, sys.argsfs.read, fs.write, fs.listnet.connect, net.bind, net.listencompute.threads, compute.simd, compute.atomichost.log, host.metrics, host.rpc// 1. Plugin declares required capabilities
plugin_manifest = {
"capabilities_required": [
"fs.read:/app/data/*",
"net.connect:api.example.com:443",
"compute.threads:4"
],
"capabilities_optional": [
"fs.write:/tmp/*",
"host.metrics"
]
}
// 2. Host evaluates and returns granted set
host_response = {
"granted": [
"fs.read:/app/data/*",
"net.connect:api.example.com:443",
"compute.threads:2" // Reduced from 4
],
"denied": [
"fs.write:/tmp/*" // Policy violation
],
"substitutions": {
"compute.threads": "4→2" // Version skew accommodation
}
}
// Semantic versioning with compatibility ranges
struct VersionVector {
host_api: VersionRange, // e.g., "1.2.x" (1.2.0 to 1.2.999)
wasm_abi: VersionRange, // e.g., ">=1.0.0 <2.0.0"
plugin_sdk: VersionRange, // Plugin's SDK version
runtime: VersionRange, // Wasmtime/WAVM version
}
// Compatibility matrix
const COMPATIBILITY_MATRIX: [(Version, Version, bool); 12] = [
(v1_0, v1_0, true), // Exact match
(v1_0, v1_1, true), // Minor version forward compatible
(v1_0, v1_2, false), // Breaking change
(v1_0, v2_0, false), // Major version incompatible
];
Plugin announces: "I need host_api >=1.2.0 <2.0.0"
Host supports: [1.0.x, 1.1.x, 1.2.x, 1.3.x]
→ Agree on 1.3.x (highest compatible)
Plugin uses: `host_api.fill_buffer(ptr, len)` v1.2 signature
Host provides: `host_api.fill_buffer(ptr, len, flags)` v1.3 signature
→ Host wraps with compatibility shim:
fn v1_2_fill_buffer(ptr, len) {
v1_3_fill_buffer(ptr, len, 0) // Default flags
}
// Auto-generated compatibility adapters
trait HostApiV1_2 {
fn fill_buffer(&self, ptr: u32, len: u32) -> Result<()>;
}
impl HostApiV1_3 {
fn as_v1_2(&self) -> HostApiV1_2Adapter {
HostApiV1_2Adapter::new(self)
}
}
struct HostApiV1_2Adapter<'a> {
inner: &'a HostApiV1_3,
}
impl<'a> HostApiV1_2 for HostApiV1_2Adapter<'a> {
fn fill_buffer(&self, ptr: u32, len: u32) -> Result<()> {
self.inner.fill_buffer(ptr, len, 0) // Compatibility shim
}
}
struct MemoryNegotiation {
// Plugin's request
plugin_request: MemoryRequest {
initial_pages: 16, // 1MB initial
max_pages: 256, // 16MB max requested
growth_strategy: "linear"
},
// Host constraints
host_limits: MemoryLimits {
system_total: 4096, // 256MB total for all plugins
per_plugin_soft: 128, // 8MB soft limit
per_plugin_hard: 256, // 16MB hard limit
emergency_reserve: 256 // 16MB reserve for host
},
// Negotiated result
agreement: MemoryAgreement {
initial_pages: 16,
max_pages: 128, // Compromised: 8MB
growth_increment: 16, // Grow by 1MB
oom_handler: "sandbox-terminate" // or "notify_host"
}
}
def negotiate_memory(plugin_req, host_limits, system_load):
# Start with plugin's request
max_pages = plugin_req.max_pages
# Apply host limits
max_pages = min(max_pages, host_limits.per_plugin_hard)
# Consider system load
if system_load > 0.8:
max_pages = min(max_pages, host_limits.per_plugin_soft)
# Emergency reserve check
available = host_limits.system_total - host_limits.emergency_reserve
max_pages = min(max_pages, available)
# Ensure initial fits
if plugin_req.initial_pages > max_pages:
return NegotiationError("Initial memory exceeds maximum")
return MemoryAgreement(
initial=plugin_req.initial_pages,
maximum=max_pages,
emergency_oom="sandbox-terminate" if max_pages < 32 else "notify_host"
)
// Plugin sends manifest
{
"plugin_id": "com.example.data-processor",
"version": "2.1.0",
"capabilities": {
"required": ["fs.read:/input/*", "compute.threads:2"],
"optional": ["fs.write:/output/*", "net.http:outbound"],
"preferred": ["host.metrics:detailed"]
},
"compatibility": {
"host_api": ">=1.2.0 <2.0.0",
"wasm_abi": ">=1.0.0",
"sdk": "2.x"
},
"resources": {
"memory": {
"initial_kb": 16384,
"max_kb": 262144,
"growth": "linear"
},
"cpu": {"shares": 100, "affinity": "any"}
}
}
struct NegotiationContext {
plugin_manifest: PluginManifest,
host_policy: Arc<PolicyEngine>,
system_state: SystemState,
version_registry: Arc<VersionRegistry>,
}
impl NegotiationContext {
async fn negotiate(&self) -> Result<Contract> {
// 1. Version compatibility
let agreed_version = self.version_registry
.find_compatible_version(
&self.plugin_manifest.compatibility
)?;
// 2. Capability filtering
let granted_caps = self.host_policy.evaluate_capabilities(
&self.plugin_manifest.capabilities.required,
&self.plugin_manifest.capabilities.optional
)?;
// 3. Memory negotiation
let memory_contract = negotiate_memory(
self.plugin_manifest.resources.memory,
self.host_policy.memory_limits(),
self.system_state.load()
)?;
// 4. Generate contract
Ok(Contract {
version: agreed_version,
capabilities: granted_caps,
memory: memory_contract,
tokens: self.generate_capability_tokens(&granted_caps)?,
expiry: SystemTime::now() + Duration::from_secs(3600),
})
}
}
// Final contract presented to plugin
{
"contract_id": "cnt_abc123",
"version": {
"host_api": "1.3.0",
"wasm_abi": "1.0.0",
"adapter": "auto" // Host provides compatibility adapters
},
"capabilities": [
{
"token": "cap:fs:read:/input/*",
"access": "read-only",
"quota": "10gb/day"
},
{
"token": "cap:compute.threads:2",
"isolated": true,
"affinity": "any"
}
],
"memory": {
"initial_pages": 16,
"max_pages": 128,
"guard_pages": 4,
"oom_policy": "soft-limit"
},
"constraints": {
"max_instructions": 1000000000, // Per second
"syscalls_per_second": 1000,
"allowed_imports": ["env.memory", "env.abort"]
}
}
// Defense in depth
┌─────────────────────────────────────────────┐
│ Sandbox Layers │
├─────────────────────────────────────────────┤
│ 1. Wasm Validation (type/control flow) │
│ 2. Capability Enforcement (per-call) │
│ 3. Memory Guard Pages (no overflow) │
│ 4. CPU Quotas (instructions/sec) │
│ 5. Syscall Filter (only allowed syscalls) │
│ 6. Network Namespace (if network access) │
│ 7. Filesystem Chroot (if fs access) │
└─────────────────────────────────────────────┘
# Capability decision
default grant = false
grant {
input.capability == "fs.read"
input.resource.matches("/app/data/*")
input.plugin.trust_level >= 0.7
}
grant {
input.capability == "net.connect"
input.resource == "api.example.com:443"
input.time in work_hours
}
# Memory limits
memory_max_pages {
input.plugin.tier == "gold"
result = 256
}
memory_max_pages {
input.plugin.tier == "silver"
result = 128
}
// Imports provided by host
[
"host.get_capability_token", // Get current token
"host.request_capability", // Request new capability
"host.get_resource_usage", // Query current usage
"host.version", // Get negotiated version
"host.heartbeat", // Keep-alive for long-running
"host.log", // Structured logging
"host.metrics", // Metrics collection
]
// Capability-specific imports (based on contract)
[
"fs.read", // Only if granted
"fs.write", // Only if granted
"net.http_client", // Only if granted
"compute.thread_spawn", // Only if granted
]
┌─────────────┐ load ┌──────────────┐ negotiate ┌─────────────┐
│ Plugin │──────────►│ Loader │───────────────►│ Negotiator│
│ Binary │ │ │ │ │
└─────────────┘ └──────────────┘ └─────┬───────┘
│ contract
▼
┌─────────────┐ instantiate ┌──────────────┐ monitor ┌─────────────┐
│ Host │◄─────────────────│ Runtime │◄────────────│ Monitor │
│ Policies │ │ Sandbox │ │ │
└─────────────┘ └──────────────┘ └─────────────┘
│ │
│ contract_violation │ oom/cpu
▼ ▼
┌─────────────┐ ┌─────────────────┐
│ Policy │ │ Auto- │
│ Violation │ │ Scale/ │
│ Handler │ │ Throttle │
└─────────────┘ └─────────────────┘
enum NegotiationError {
VersionIncompatible {
plugin: String,
host: String,
matrix: Vec<CompatibilityIssue>
},
CapabilityDenied {
required: Vec<String>,
denied: Vec<String>,
reason: DenialReason
},
MemoryExceeded {
requested: u64,
available: u64,
suggestion: String
},
PolicyViolation {
rule: String,
detail: String
}
}
enum RuntimeError {
OOM,
CPUQuotaExceeded,
CapabilityViolation(String),
VersionSkew(String), // Runtime detected version mismatch
ContractBreach(String) // Token validation failed
}
// build.js - Build with capability declarations
const { buildPlugin } = require('@host/sdk');
buildPlugin({
entry: './src/index.ts',
capabilities: {
required: [
'fs.read:/config/*',
'net.http:client:*',
'compute.threads:2'
]
},
version: '2.1.0',
target: 'host-api-1.2+'
});
# host-policy.yaml
plugins:
default_contract:
memory:
max_pages: 128
oom_policy: "terminate"
capabilities:
auto_grant:
- "host.log:*"
- "host.metrics:basic"
deny:
- "fs.write:*"
- "net.bind:*"
com.example.data-processor:
tier: "gold"
memory:
max_pages: 256
capabilities:
auto_grant:
- "fs.write:/output/*"
quota:
"fs.read": "100gb/day"
com.example.untrusted:
tier: "sandbox"
memory:
max_pages: 64
capabilities:
deny_all: true
allow:
- "fs.read:/sandbox/*"
Host API v1.0 ──────────────────────────► Current
│ │
│ Auto-adapter │ Auto-adapter
▼ ▼
Host API v0.9 ◄── Compatibility shim ── Legacy plugins
│
│ Manual adapter (if needed)
▼
Host API v0.8 ◄── Deprecated shim ─── Very old
This design provides a robust, secure foundation for WebAssembly plugin ecosystems with proper version management and resource control. The token-based capability system allows fine-grained permissions, while the version negotiation with adapter generation handles long-term evolution of both host and plugin APIs.