Skip to content

Modules in a sandbox

A module is a small WebAssembly program that your app runs in a sandbox, so you can change license-bound logic, such as how a quote is calculated or which rules apply to a plan, without a new app release. Only modules that you signed run. Noctix never signs a module and never holds the key, so not even a compromised server can slip one into your app (protocol, section 6.18).

Test version. The runtime is the Rust crate sdk-modules (alpha), also offered by the C, C++, C#, Python and Java SDKs. It stays a test version until an external review of the sandbox is done.

Use a module for logic that may change. Do not use it to protect a secret: a module ships to the device like any file and can be copied and read. Values that must stay secret belong on your server, for example behind a proxy target.

What a module can and cannot do

A module can A module cannot
Compute on the bytes your app passes in and return bytes Read or write files, open network connections, start processes
Call the functions your app registers, by name, with bytes in and out Call anything else: WASI, a clock, randomness and every other import are refused before it runs
Keep state in its own memory between calls of one instance See the memory of the app, of the SDK or of another instance

Every call has limits. When a module exceeds one, the call fails, the app keeps running, and that instance refuses further calls (create a new one):

Limit Default Highest you can set
Fuel per call (about one unit per instruction, app functions included) 100,000,000 10,000,000,000
Memory of one instance 16 MiB 256 MiB
Input and output of one call, each 1 MiB 16 MiB
Size of the module 4 MiB 4 MiB

The runtime is an interpreter (wasmi). It does not generate machine code, so it runs everywhere the SDK runs, iOS included, and adds no executable memory to your app. Threads, SIMD, 64-bit memory, several memories, exceptions, tail calls, garbage collection and start functions are off; a module that uses them is refused.

1. Write a module

The module and your app talk through a small ABI (version 1):

  • The module exports its memory as memory and a function alloc(len: i32) -> i32 that returns a buffer of len bytes.
  • Every function your app calls has the type (ptr: i32, len: i32) -> i64: it reads its input at ptr, len bytes long, and returns its output packed as (out_ptr << 32) | out_len.
  • A function of your app that the module calls is imported from the namespace app with the same type. The runtime copies the output into a buffer from the module's alloc.

A complete example in Rust, which asks the app for the price of a seat and returns a quote, is in crates/sdk-modules/guest-example. Build it with:

cargo build --release --target wasm32-unknown-unknown

Any language that compiles to WebAssembly works if it follows the ABI.

2. Sign it in your pipeline

Modules use the same key as releases signed by you. If you have none yet, create one with release-tool keygen and keep the private key as RELEASE_KEY in your pipeline's secrets.

RELEASE_KEY=... release-tool sign-module prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5 live quote 1.0.0 guest_example.wasm > quote.token

The token names the product, the environment, the module's name and version, and the size and SHA-256 of exactly this file. Change one byte and the module no longer runs.

3. Ship it

Ship the module and its token together: in the app bundle, or as an asset so you can change it without a release. For an asset, turn on the product setting modules (off by default) and upload with the token next to the file:

release-tool asset --product prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5 --name quote-1.0.0 --visibility public \
  --module-token quote.token guest_example.wasm

The server takes the module only if the token verifies with one of your product's release keys and names this product, environment, size and SHA-256. The download of the asset carries the token as module_token. Assets are only handed over; the SDK never runs a file it downloads. Your app decides to pass file and token to the runtime, which checks the token again with the keys in the app.

4. Run it in the app

Every SDK follows the same steps: create a runtime with your release keys, register the functions modules may import, load the module with its token (this verifies it, nothing runs yet), create an instance and call its exports.

Rust

use sdk_modules::{Environment, Limits, Runtime};

let runtime = Runtime::new(
    "prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5",
    Environment::Live,
    &["k4.public.…active…", "k4.public.…reserve…"], // your release keys
)?
.with_function("seat_price", |_input| Ok(b"1500".to_vec()))?
.with_min_version("quote", "1.0.0")?
.with_limits(Limits::default())?;

let module = runtime.load("quote", &wasm_bytes, &token)?; // verifies, nothing runs yet
let mut instance = module.instantiate()?;
let total = instance.call("quote", b"10")?; // b"13500"

load refuses, before a byte of the module is parsed:

  • a token that does not verify with your keys (Token(key_unknown), Token(signature_invalid), …), including any token Noctix signed;
  • a token for another module name (NameMismatch) or a version below with_min_version (VersionTooOld), so an older module you once signed cannot be put back;
  • bytes that differ from the token (DigestMismatch).

After that it refuses a module that is not valid, uses a feature that is off (Invalid), imports anything but your registered functions (ImportDenied) or lacks memory and alloc (Abi). A call fails with OutOfFuel, MemoryLimit, Trap, IoTooLarge, Abi (a pointer outside the module's memory), ExportMissing or Host (your function returned an error). Your functions run while the module waits; a module cannot call one of them from inside another.

Error codes in the other SDKs

The other SDKs report the same failures as errors with a stable code. Token failures have the kind verify and the token's code (key_unknown, signature_invalid, …); a limit above the highest you can set has the kind config and the code config_invalid. Everything else has the kind module:

Code Meaning
module_name_mismatch, module_version_too_old, module_digest_mismatch The token names another module, a version below the minimum, or other bytes
module_invalid, import_denied, abi_violation Not a valid module, a feature that is off, an import that is not yours, or a broken ABI
export_missing, io_too_large No such export, or input or output above the limit
out_of_fuel, memory_limit, module_trap The call used up its fuel or memory, or the module trapped
host_error Your function failed; the message is the text it gave
instance_poisoned An earlier call on this instance failed; create a new one

The prebuilt libraries contain the runtime. To leave it out, build sdk-ffi with --no-default-features --features http,os-store; the lsdk_module_* functions are then missing and the wrappers fail when you use them.

C

static int seat_price(void *user_data, const uint8_t *input, size_t len, lsdk_buffer *out) {
    return lsdk_buffer_set(out, (const uint8_t *)"1500", 4) ? LSDK_CALLBACK_OK : LSDK_CALLBACK_ERROR;
}

lsdk_module_runtime *rt = NULL;
lsdk_error *err = lsdk_module_runtime_new("prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5", LSDK_ENVIRONMENT_LIVE,
                                          "k4.public.…active…", "k4.public.…reserve…", &rt);
lsdk_module_function f = {.user_data = NULL, .call = seat_price, .release = NULL};
err = lsdk_module_runtime_add_function(rt, "seat_price", f);
err = lsdk_module_runtime_set_min_version(rt, "quote", "1.0.0");

lsdk_module *module = NULL;
err = lsdk_module_runtime_load(rt, "quote", wasm, wasm_len, token, &module);
lsdk_module_instance *inst = NULL;
err = lsdk_module_instantiate(module, &inst);
lsdk_module_output *total = NULL;
err = lsdk_module_instance_call(inst, "quote", (const uint8_t *)"10", 2, &total);
/* lsdk_module_output_data(total), lsdk_module_output_len(total): "13500" */
lsdk_module_output_free(total);
lsdk_module_instance_free(inst);
lsdk_module_free(module);
lsdk_module_runtime_free(rt);

Check every err as usual (left out above). lsdk_module_runtime_set_limits(rt, fuel, memory, io) sets the limits, 0 keeps a default. A function that fails returns a negative value; text it put into out becomes the message of host_error. The SDK calls release once, when the runtime and every module loaded with the function are freed, and also when lsdk_module_runtime_add_function fails. A module and its instances stay usable after the runtime is freed. Calls on one instance must not overlap.

C++

lsdk::ModuleRuntime rt("prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5", lsdk::Environment::Live,
                       "k4.public.…active…", std::string("k4.public.…reserve…"));
rt.add_function("seat_price", [](const uint8_t*, size_t) {
    return std::vector<uint8_t>{'1', '5', '0', '0'};
}).set_min_version("quote", "1.0.0");

lsdk::Module module = rt.load("quote", wasm, token);  // std::vector<uint8_t>
lsdk::ModuleInstance inst = module.instantiate();
std::vector<uint8_t> total = inst.call("quote", "10");  // "13500"

A function that throws fails the call with host_error and the exception's what(). Failures throw lsdk::Error with kind() lsdk::ErrorKind::Module (or Verify, Config) and code().

C#

using var rt = new ModuleRuntime("prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5", LicenseEnvironment.Live,
                                 "k4.public.…active…", "k4.public.…reserve…")
    .AddFunction("seat_price", input => "1500"u8.ToArray())
    .SetMinVersion("quote", "1.0.0");

using Module module = rt.Load("quote", wasm, token);
using ModuleInstance inst = module.Instantiate();
byte[] total = inst.Call("quote", "10"); // "13500"

SetLimits(fuelPerCall, memoryBytes, ioBytes) sets the limits, 0 keeps a default. A function that throws fails the call with host_error and the exception's message. Failures throw LicenseException with Kind LicenseErrorKind.Module (or Verify, Config) and Code. Calls on one instance run one at a time.

Python

from license_sdk import Environment, ModuleRuntime

rt = (
    ModuleRuntime("prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5", Environment.LIVE, "k4.public.…active…", "k4.public.…reserve…")
    .add_function("seat_price", lambda data: b"1500")
    .set_min_version("quote", "1.0.0")
)
with rt.load("quote", wasm, token) as module, module.instantiate() as inst:
    total = inst.call("quote", b"10")  # b"13500"

set_limits(fuel_per_call=, memory_bytes=, io_bytes=) sets the limits, 0 keeps a default. A function that raises fails the call with host_error and the exception's text. Failures raise LicenseError with kind ErrorKind.MODULE (or VERIFY, CONFIG) and code. Calls on one instance run one at a time.

Java

try (ModuleRuntime rt = new ModuleRuntime("prod_01HZX3V5Q8N4R2M6K9T7W1Y3B5", LicenseEnvironment.LIVE,
                "k4.public.…active…", "k4.public.…reserve…")
            .addFunction("seat_price", input -> "1500".getBytes(StandardCharsets.UTF_8))
            .setMinVersion("quote", "1.0.0");
        LoadedModule module = rt.load("quote", wasm, token);
        ModuleInstance inst = module.instantiate()) {
    byte[] total = inst.call("quote", "10"); // "13500"
}

The loaded module is a LoadedModule, so the name does not clash with java.lang.Module. setLimits(fuelPerCall, memoryBytes, ioBytes) sets the limits, 0 keeps a default. A function that throws fails the call with host_error and the exception's message. Failures throw LicenseException with kind() LicenseErrorKind.MODULE (or VERIFY, CONFIG) and code(). Calls on one instance run one at a time.

In Rust the crate is separate from sdk-core. If your app does not depend on it, it contains no module runtime at all.