function-wasm
The sandbox hasn’t had an independent security review. From 1.0.0 the Input, the guest ABI, the runtime flags and the rest of what Compatibility lists change through its deprecation policy alone. Before it they could change between minor releases.
This page is for Crossplane users deciding whether to run composition logic as WebAssembly modules. It assumes you know Compositions and pipeline mode.
function-wasm is a Crossplane composition function
that runs a WebAssembly module in a Wasmtime sandbox.
A module follows the contract of a native function,
RunFunction(RunFunctionRequest) → RunFunctionResponse. You write an ordinary
function in Go (with
function-sdk-go), Rust,
TypeScript or Python, compile it to WebAssembly, publish the module
and point a Composition step at it.
It fits when the logic of a pipeline step should change without a new Function package, or when the people who maintain that logic aren’t the people who maintain the Composition. One installed function-wasm serves any number of modules, so a new module version is a new reference in the Input.
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
name: example
spec:
compositeTypeRef:
apiVersion: example.crossplane.io/v1
kind: XR
mode: Pipeline
pipeline:
- step: greet
functionRef:
name: function-wasm
input:
apiVersion: guestfn.crossplane.io/v1
kind: Input
module:
type: OCI
oci:
ref: ghcr.io/example/greeter:v1@sha256:4c9d… # printed by guestfn push; the digest pins the module, the tag is for humans
config:
greeting: hi
The module receives the whole RunFunctionRequest and returns the whole
RunFunctionResponse, so desired resources, results, conditions, requirements
(extra resources), context and TTL pass through as they do for a native
function. The runtime withholds the step credentials a module wasn’t
granted, and no others.
Where to go next
- Write a module to scaffold, build and publish a guest. Other languages lists the rest.
- Install the runtime to run function-wasm in a cluster.
- Install function-oci and OCI modules for the second runtime, which runs an OCI image in a microVM under the same Input, manifest and policy layers.
- A request, step by step to see what the runtime does between Crossplane’s request and the module’s response.
Use cases
This page is for platform engineers and composition authors deciding whether function-wasm fits a pipeline step. It lists what the runtime suits, where its limits are and the examples that show it. It assumes you know Crossplane compositions. The introduction covers what function-wasm is.
function-wasm suits a step whose logic should change without building, publishing and installing a Function package. It also suits a step whose logic someone other than the Composition’s author maintains.
- A customization hook at the end of a pipeline. The platform team
publishes the Composition and reserves its last step for the module each
composite resource names in
module.from; withallowEmpty: truethe step does nothing until the field is set. That team changes labels, sizing or sidecars in its own language, without a change request against the Composition. The platform team keeps the guardrails: the digest pin and thecompositionPolicyfence on repositories in the Input, and the operator’s signature check. - Policy gates. A module that runs last sees the complete observed and desired state. It can check the composed resources against organisational rules such as naming, mandatory tags or allowed regions. A fatal result stops the reconcile, and a warning leaves a trace without stopping it.
- Fast iteration and rollback. Write the function,
guestfn build, render locally,guestfn pushand reference the digest in the Composition. Rolling forward or back is a digest change in that Composition; nothing is reinstalled. - Small functions, one runtime. Each team maintains its own modules, in any of the supported languages. The cluster runs one function-wasm, which compiles each module once per digest and caches it.
- Restricted networks. Modules can come from an internal registry, an
internal HTTP server (
http) or a volume mounted into the runtime (path). The runtime keeps fetched modules and compiled code on disk, so with a volume at/tmp/guestfn-cachea module it has already fetched keeps running across restarts while the registry is down, unless a signature is required: the runtime verifies that over the registry once per process. A module it has never fetched can’t be loaded.
Limits
By default a module doesn’t get network, filesystem or environment access; cluster state comes in through the request and the module returns desired state. A module can request more in its manifest. The runtime grants the request when the Composition’s policy and the operator’s policy both permit it and withholds it otherwise. See HTTP egress and the trust model.
function-wasm doesn’t support Crossplane Operations: its package declares
the composition capability alone.
Worked examples
Each example under
examples/
is a guest in one language that solves one of these cases. The end-to-end
workflow builds, tests and lints them on a pull request labelled
e2e:wasm:examples or e2e:oci:examples, but nothing in CI asserts what an
example composes. The design record for the use-case examples
explains why these were chosen and how they’re published.
Publish Examples publishes function-wasm-rust, function-wasm-ts,
function-wasm-go and function-oci-go to
ghcr.io/jonasz-lasut/guestfn/examples/<runtime>-<lang> (wasm-rust,
wasm-ts, wasm-go, oci-go), signed and attested, when the
version in the example’s guestfn.yaml isn’t in the registry yet. guestfn inspect <ref> prints the digest-pinned reference for a Composition.
examples/function-wasm-rust(Rust): an origin accepts connections from Cloudflare alone. The module composes the origin’s AWS security group and one ingress rule per range Cloudflare publishes, read at reconcile time through the host’s egress - a capability its manifest requests and both policy layers must grant.examples/function-wasm-ts(TypeScript): the organisation’s policy as the last pipeline step. The module asks Crossplane for the environment’s EnvironmentConfig throughrequirements. It adds its mandatory tags to every composed resource without overwriting the team’s and refuses a region or instance class the environment doesn’t allow - one digest-pinned module the platform team rolls out on its own.examples/function-wasm-go(Go): a customization hook at the end of a pipeline. AWebAppComposition reserves its last step for the add-on eachWebAppnames inspec.addOn(module.from, skipped while unset), fenced to one repository by thecompositionPolicy; this add-on gives every Deployment the platform composed a PodDisruptionBudget, in the default sandbox, with no capability at all.examples/function-wasm-python(Python): a team’s owner and cost center come from the CMDB, never from the composite resource. After function-go-templating composes an S3 bucket, the module reads the record of the team the namespace of the composite resource belongs to, with that team’s token from a step credential holding every team’s, and stampsteam,ownerandcost-centertags on every composed managed resource. The module receives that credential where its manifest requires it and both policy layers permit it, and nowhere else.examples/function-wasm-cpp(C++): a TLS Secret’s self-signed certificate, kept fresh. AServerCertificatenames the Secret, the DNS names and the validity; the module asks Crossplane for the Secret through the response’srequirements, reads the certificate in it and composes the Secret again, with a fresh P-256 key and self-signed certificate once fewer thanrenewBeforeDaysremain. The Composition scopes both fences a response meets: the module may read Secrets of its own namespace by name and compose Secrets, and any other ask or kind is refused.examples/function-wasm-csharp(C#): dashboards as code, delivered as a bundle. A composite resource pins a team’s zip of Grafana dashboards by sha256; the module fetches it through the host’s egress and refuses any other content, then unpacks it into its private/tmpand composes one ConfigMap per dashboard for Grafana’s sidecar - the two capabilities its manifest requests.examples/function-oci-go(Go, an OCI module): the hello function as an image that the OCI runtimefunction-ociboots in a microVM once per request.main.gostarts function-sdk-go’s server around an ordinary function, andguestfn push --imageappends the manifest to the image (OCI modules).
A request, step by step
This page is for someone evaluating function-wasm. It follows one Crossplane request through the runtime, so you can see what’s checked before a module runs, what the module can do and how a failure ends. It assumes you know what function-wasm is. Each step links to the page with the detail.
A module gets a capability when three layers agree, and not otherwise. The module’s
manifest has to request it, and the
Composition’s compositionPolicy and the operator’s policy, the Cedar file
named by --sandbox-policy-file, both have to permit it. The
design record has the reasoning.
1. Admission
The runtime decodes the Input, compiles the compositionPolicy and checks
limits against its ceilings. Malformed Cedar, or a timeout or memory
limit over its ceiling, is a fatal result. A concurrency limit over its
ceiling is capped, with no error. A step that takes its module from the composite
resource (module.from) is fenced by the compositionPolicy: pullModule
for the repository, spendCredential for a credential. The fields are in the
Input reference.
An OCI or HTTP source is pinned by digest and a path source is hashed by
content, so resolving a module never waits on a registry.
2. Loading
Where the operator requires a signature, the runtime verifies it first, once per repository and manifest digest per process and before any cache (signatures).
The runtime then looks the digest up in the compiled modules in memory (kept ten minutes after last use), the Wasmtime artifacts on disk and the fetched modules on disk. The runtime fetches a module this pod has never seen, checks it against its digest and compiles it. Any other module skips these steps. A component that fails the world’s typecheck is refused here, and so is a core module, the ABI v1 shape removed in 1.0.0. The stores are described under cache storage. The cache design record has the reasoning.
The runtime then checks the manifest, if the module has one, against the other
two layers. A requires entry that isn’t permitted, or a config outside the
module’s schema, is a fatal result before anything runs.
3. Running
Each request runs in a fresh instance. The module receives the caller’s
request, less every step credential it wasn’t granted. It gets WASI
without network access. The filesystem is a private /tmp removed after the
request, and the environment variables are those its manifest binds to step
credentials, if the three layers granted them.
Granted HTTP requests go through the host (HTTP egress). Guest logs go to the runtime’s logger with the module reference attached, and stdout and stderr go to the pod’s log.
4. Response
The runtime returns the response as the module produced it, after two
fences. Where a policy layer scopes requireResource, every resource selector
in the response’s requirements must be permitted
(the read fence). Where one scopes
composeResource, every change to the desired state must be permitted
(the output fence). A refused
selector or change is a fatal result that specifies the kind, the name, the
entry or change and the layer.
A trap, a timeout, the memory limit or an unusable module is also a fatal
result, and the function pod keeps running. The timeout is wall-clock time,
whether the guest computes or waits in a WASI call. The time it waits for
the host’s HTTP answers is credited back. A request
whose deadline passes while it waits for a run slot gets
waiting for a run slot: deadline exceeded and never runs.
Troubleshooting lists the results and their
causes.
The full host and guest contract is in ABI v2.
Install function-wasm
This page is for operators adding function-wasm to a cluster that already runs Crossplane. It installs the function package and checks that Crossplane accepted it.
Apply a Function with the package reference:
apiVersion: pkg.crossplane.io/v1
kind: Function
metadata:
name: function-wasm
spec:
package: ghcr.io/jonasz-lasut/function-wasm:v1.1.0
The same package is published to xpkg.upbound.io/jonasz-lasut/function-wasm, for clusters that pull from xpkg.upbound.io. Both copies are signed, and Verifying a function package has the command and the signer’s identity.
One installed function serves any number of modules: a Composition step puts its module reference in the step’s Input, so adding a module needs no further install.
Crossplane supports the three most recent minor releases, and function-wasm supports the same three. Pushing a release branch runs the end-to-end suite on all three, and a release is cut when that run is green and not before (the release matrix lists the versions).
Check the install
Crossplane pulls the package and starts the function’s pod. The function is ready when INSTALLED and HEALTHY are both True:
kubectl get function function-wasm
If it stays unhealthy, read the pod’s logs and the Function’s conditions (kubectl describe function function-wasm). Troubleshooting lists the runtime’s own refusals.
The side ports
The function port speaks mTLS to Crossplane. /metrics on 8080 and the
probes on 8081 are plain HTTP. Their answers contain no secret and no
module name, and nothing authenticates a caller. The runtime closes a
connection that hasn’t sent its request within five seconds. Admit the ports from nowhere but
where they’re read. A NetworkPolicy on the function’s pods, which
Crossplane labels pkg.crossplane.io/function: function-wasm, admits the
metrics port from the monitoring namespace and leaves the probe port to the
kubelet:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: function-wasm-side-ports
namespace: crossplane-system
spec:
podSelector:
matchLabels:
pkg.crossplane.io/function: function-wasm
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
ports:
- port: 8080
- ports:
- port: 8081
The probe rule admits 8081 from anywhere, because the kubelet’s probes
come from the node’s address, which a namespaceSelector can’t name. Most
network plugins let the kubelet’s probes through whatever the policy says;
where yours doesn’t, replace that rule with an ipBlock of the node CIDR.
The function port isn’t in the policy, so Crossplane keeps reaching it.
Next steps
A fresh install runs every module in the default sandbox, which gives a module no network, filesystem or environment beyond the request (trust model).
- Set flags, such as limits and caches, through a
DeploymentRuntimeConfig: see runtime flags. - Keep the caches across restarts on a volume that this Function’s pods alone mount: see cache storage.
- Add readiness and liveness probes and pre-load modules: see readiness and warm-up.
- Require signed modules: see signatures.
- Allow a module more than the default sandbox, such as egress or a private
/tmp: see the grant policy. - Admit the metrics and probe ports from their readers alone: see the side ports.
Write a module
This page is for a module author. It takes you from guestfn init to a module
published as an OCI artifact, using the Go scaffold as the worked example. The
other scaffolds (--lang rust, ts or python) use the same commands. See
Other languages for what differs, and for the languages
that exist as examples alone.
Install the CLI and scaffold a project:
# Prebuilt, from a guestfn-v* release (guestfn-linux-amd64, -linux-arm64, -darwin-amd64 or -darwin-arm64):
curl -fsSLo guestfn https://github.com/jonasz-lasut/guestfn/releases/download/guestfn-v0.3.0/guestfn-linux-amd64 && chmod +x guestfn
# Or from source:
cargo install --git https://github.com/jonasz-lasut/guestfn guestfn
guestfn init greeter --module github.com/example/greeter # --lang go (default), rust, ts or python
cd greeter
guestfn init reads the tags of ghcr.io/jonasz-lasut/function-wasm and
writes the newest release of the CLI’s own major into
example/functions.yaml. --function-version states the release, and
--repository names another repository to read, with the credential the
Docker keychain has for its registry. With --offline, or when the
registry doesn’t answer within 3 seconds, the CLI writes the release built
into it and says so.
The Go scaffold writes fn.go, fn_test.go and main.go. fn.go is a
plain function-sdk-go RunFunction that composes a ConfigMap greeting the
composite resource, with no code specific to WebAssembly. main.go does nothing but
register it:
func init() {
wasmfn.Register(&Function{log: wasmfn.NewLogger(), http: wasmfn.HTTPClient()})
}
func main() {}
The glue is a small internal/wasmfn package that the project owns. It
exports run for the ABI v2 world: it decodes the request,
calls your RunFunction and encodes the response. It also provides a
logging.Logger over the runtime’s typed log import, and
wasmfn.GetConfig(req, &cfg) to read the module’s configuration, which the
runtime reads from the composite resource field the step’s config.from
names and hands over as input.config. The Go
bindings under internal/bindings are written by
wit-bindgen and checked in.
examples/function-wasm-go
is a Go module built on what guestfn init writes. Its internal/wasmfn,
wit/ and internal/bindings are the scaffold’s, byte for byte.
Build, inspect and publish
go test ./... # unit tests run natively
guestfn build # fn.wasm (an ABI v2 component); prints the ABI verdict and the manifest summary
guestfn inspect fn.wasm # size, ABI verdict, exports, imports
guestfn push ghcr.io/example/greeter:v0.1.0 # OCI artifact with the manifest; prints the module block and what the module requires
guestfn build runs go build, embeds the world from wit/ and wraps the
result into a component. It then compiles the component with the runtime’s own
Wasmtime engine and prints the verdict a load gives. For the Go scaffold
the output is a Componentized fn.wasm (wasip1 adapter linked) line, then a
Built line with the file, its size, ABI v2, the world’s imports and the
manifest summary.
A module the runtime would refuse fails the build with the runtime’s own
words, and guestfn push refuses to publish it for the same reason. The
refusals are listed in Troubleshooting.
guestfn inspect fn.wasm shows what the runtime sees: size, verdict,
exports and imports. guestfn inspect ghcr.io/example/greeter:v0.1.0
describes a published artifact from its manifest without pulling it, and
--pull reads the module too. --output json prints JSON for scripts.
Manifest
The scaffold includes a guestfn.yaml, the module’s manifest. It gives the
module a name and version, declares the sandbox capabilities the module can’t
run without, and contains the JSON Schema of its config. guestfn build
validates it and guestfn push publishes it beside the module. See
Module manifests for the fields and for how the runtime
checks a module’s requirements.
guestfn scaffold composition --from ghcr.io/example/greeter:v0.1.0 (or
--from fn.wasm) writes a Composition step for the module, pinned by digest,
with config.from: spec.config, a commented definition fragment with the
schema for that field, and a commented compositionPolicy skeleton. The policy block is a commented starting point for narrowing.
--full writes a whole Composition.
What guestfn push publishes
guestfn push produces a CNCF Wasm OCI artifact: one application/wasm
layer, the manifest as an application/vnd.guestfn.manifest.v1+json layer
when the project has one, a config object listing both digests in
layerDigests, and the standard org.opencontainers.image.* annotations
from the manifest.
oras push ghcr.io/example/greeter:v0.1.0 fn.wasm:application/wasm guestfn.json:application/vnd.guestfn.manifest.v1+json gives the same result.
A FROM scratch image with one layer that copies the module to /fn.wasm works
too, without a manifest. The runtime reads that exact path and doesn’t search
the archive.
Module size
A Go module that uses function-sdk-go’s helpers is about 75 MB. See Sizing for what that costs the runtime.
Other languages
This page is for a module author choosing a guest language. It lists the four
flavours guestfn init scaffolds, the guests that exist as examples alone, and
what the project hasn’t tested. Pick a flavour, scaffold it, then follow Write
a module. Any toolchain that produces a component for the
ABI v2 world, guestfn:function, works: the runtime checks the
world and never the language.
Scaffolded flavours
guestfn init --lang <flavour> writes the same greeting function in each of
these, the languages with an official function-sdk-<lang> under the
crossplane GitHub organisation, and guestfn build detects the toolchain from the
project. All four build an ABI v2 component. The guest suite runs them
through the host on every pull request, and the example build jobs build,
test and lint them on a pull request labelled e2e:wasm:examples. The sizes
are of the built module.
--lang | example | toolchain | Protobuf codec | module size |
|---|---|---|---|---|
go (default) | examples/function-wasm-go | Go | function-sdk-go’s request/response/resource helpers | ~75 MB |
rust | examples/function-wasm-rust | Rust 1.100+, target wasm32-wasip3, cargo and protoc | prost over the vendored proto | ~240 KB scaffolded, ~315 KB for the example |
ts | examples/function-wasm-ts | node and npm | protobuf-es over the vendored proto | ~14 MB (SpiderMonkey) |
python | examples/function-wasm-python | python3 | protoc’s Python codec on the pure-Python protobuf runtime | ~21 MB (CPython) |
Each flavour keeps its ABI glue in the project, so you own and can edit it. The
sections below give each toolchain and how guestfn build finishes the
component.
Go
The scaffold vendors internal/wasmfn over the Go bindings that
wit-bindgen writes under
internal/bindings. Both are checked in. make gen-bindings regenerates them
with wit-bindgen-cli 0.63.0. Your function is a plain function-sdk-go
RunFunction. go build emits a wasip1 reactor, and guestfn build embeds the
world from the project’s wit/ and wraps the result into a component. run is
sync-lifted, and an *http.Client reaches the host’s egress over
wasi:http@0.2.
Rust
The rust flavour needs Rust 1.100 and the wasm32-wasip3 target. The
scaffold’s rust-toolchain.toml pins the toolchain, which your Rust installer
fetches on first use. run is async, and a fetch awaits wasi:http. See ABI
v2 for the world.
TypeScript
npm install is the whole toolchain. esbuild
bundles the guest, and jco
componentizes it with componentize-js. The types come from protobuf-es, the test
gate runs tsc --noEmit, and the greeting comes from the platform’s fetch(),
served over wasi:http@0.2 through the same egress policy as every other guest.
run is sync-lifted because componentize-js can’t async-lift a custom world
yet, and your TypeScript can still await. The scaffold has no
package-lock.json: guestfn build runs npm install without one and npm ci
with one.
Python
componentize-py is the
toolchain, and guestfn build makes the venv from requirements.txt when the
project has none. The guest bundles the pure-Python protobuf runtime, and
run is sync-lifted. Fetches go over wasi:http@0.2 on the poll loop of
componentize-py, through the same egress policy.
How build chooses a toolchain
guestfn build reads the project: Cargo.toml selects cargo, build.zig
selects zig (the Zig, C, C++ and Odin examples, and any project zig build
compiles), package.json selects npm, requirements.txt selects
componentize-py, go.mod selects go, and moon.mod or moon.mod.json
selects moon. --lang overrides the choice, and build also accepts zig,
c and moonbit, which init doesn’t scaffold.
When a build leaves a core module, guestfn build wraps it into a component
with the wasip1 adapter of the runtime’s own Wasmtime, which is the adapter
version the runtime was built with. A zig build that links wit-bindgen’s C
bindings already leaves a core module with the component-type section, and
guestfn build wraps it directly. For go and MoonBit, wit-bindgen writes
bindings alone, so guestfn build embeds the world from wit/ first.
Examples without a scaffold
These guests solve their own use case or show one more language. Each has unit
tests in its language and a build job that checks its generated code for drift.
guestfn init scaffolds none of them: guestfn build detects Zig, C, Odin and
C++ by their build.zig and MoonBit by its moon.mod, and not C#. Each has
the plumbing in its own tree (the vendored proto, the codec, the bindings, the
WIT and the glue), so copy the example to start from it.
- Zig:
examples/function-wasm-zig, ~60 KB, built with Zig 0.16 bymake build. It talks Protobuf through zig-protobuf over the vendored proto and reads wit-bindgen’s C bindings, checked in undersrc/gen, through translate-c. The glue issrc/wasmfn.zig.zig buildlinks a core module without libc, andguestfn buildwraps it into a component without an adapter orwasm-tools.zig build testruns the unit tests natively. Its scaffold retired on 2026-11-08 (#264). - C:
examples/function-wasm-c, ~62 KB, compiled byzig ccbehindbuild.zigbymake build. Zig 0.16 is its whole C toolchain. It talks Protobuf through nanopb over the vendored proto and links the same C bindings. The glue issrc/wasmfn.c. The core module imports no wasip1, andguestfn buildwraps it without an adapter.protocandnanopb_generatorare needed to regenerate the codec alone,wit-bindgenfor the bindings alone.zig build testruns the unit tests natively. Its scaffold retired on 2026-11-08 (#264). - C#:
examples/function-wasm-csharp, ~4.5 MB, needs the .NET 10 SDK.make buildcompiles it with NativeAOT-LLVM and componentize-dotnet, in the .NET SDK container on macOS, which has no NativeAOT-LLVM compiler. - Odin:
examples/function-wasm-odin, ~71 KB, built with Odin dev-2026-11 and Zig 0.16 bymake build. It reuses the C example’s bindings, nanopb codec, WIT and proto. Odin compiles the guest to an object,zig cclinks it with the C half, andguestfn buildtreats the project as acone and wraps it without an adapter.make testruns the unit tests natively. - C++:
examples/function-wasm-cpp, ~160 KB, built with Zig 0.16 bymake build. It reuses the C example’s bindings, nanopb codec, WIT and proto, with a C adapter over the generated structs (nanopb names a fieldnamespace, which C++ can’t include) and the function’s logic in C++ over mbedTLS, both fetched bybuild.zig.zon.zig c++compiles the logic with libc++ forwasm32-wasi, no exceptions and no RTTI, andguestfn buildtreats the project as acone and wraps it with the wasip1 adapter for the clock and the randomness it imports.make testruns the unit tests natively. - MoonBit:
examples/function-wasm-moonbit, ~107 KB, built withmoon(version0.1.20260920). It uses wit-bindgen’s MoonBit bindings and the protoc-gen-mbt codec, regenerated bymake gen-bindingsandmake gen-proto.guestfn builddetects it bymoon.mod, embeds the world stated as UTF-16, MoonBit’s string encoding, and wraps it without an adapter. The unit tests run onmoonrun. A guest must never callprintln: it importsspectest.print_char.
Untested
- TinyGo: the scaffold was retired on 2026-10-07 (#114). The
goflavour is the Go path. - AssemblyScript: not supported, because it has no component path.
Render locally
This page is for a module author with a scaffolded guest project who wants to
see what their Composition produces before publishing anything. It runs the
runtime built from a checkout of this repository against a Path module on
your machine. Installing the runtime in a cluster is out of scope.
You need the crossplane CLI, Docker (the render engine runs in it) and a
Rust toolchain to build the runtime from the checkout.
Use two terminals. In the checkout, start the runtime with
--module-dir set to your project directory (an absolute path is simplest):
cargo run --release -p function-wasm -- --insecure --debug --module-dir=<your project directory>
In your project directory, build the module and render with the Development
runtime that the scaffold’s example/functions.yaml declares:
guestfn build
crossplane render example/xr.yaml example/composition.yaml example/functions.yaml
The example Composition uses module.type: Path with path: fn.wasm. For a
cluster, use type: OCI with an oci reference, as the
Input reference describes.
Rendering asserts nothing. To run this loop on the examples in this repository, see the development guide.
Sizing
This page is for operators choosing CPU, memory and disk for a function-wasm pod. It gives the formulas first and the measurements they rest on after. Those are the module sizes and costs, by guest toolchain, that the formulas take as inputs.
What a request and a module cost depends on the guest’s toolchain, and the Measurements section gives the per-toolchain figures the formulas use.
Memory
Budget a pod’s memory as the sum of three terms:
- the resident compiled modules;
--max-concurrent-compilestimes the peak memory of compiling your largest module (about 1 GB for a large Go module, far less for Rust, per Measurements);- concurrent runs times the per-run figure (about 16 MB for a large Go module, per Measurements).
--max-concurrent-runs caps the third term, which is useful when the callers’ concurrency isn’t the number you want to size for.
Cold start
A cold start compiles every module once. --module-size-limit bounds a
compile’s input, --max-concurrent-compiles the number that run at once (each
about 1 GB at peak for a large Go module, per Measurements) and
--module-compile-timeout how long one may take. The request’s own deadline
doesn’t cut a compile short, so leave --max-concurrent-compiles times that
peak in the pod’s memory limit. Every process compiles its modules again, with or without a volume. A volume under /tmp/guestfn-cache keeps the fetched modules, and a restart pulls nothing. The compiled code is signed per process (cache storage). --warm-modules moves the compile ahead of readiness, as readiness describes.
Disk
Disk grows by one module and one compiled artifact per digest ever served, until --max-cache-size bounds it.
Throughput
Runs execute in parallel up to --max-concurrent-runs and a step’s limits.concurrency. The --max-total-run-memory pool bounds the number of runs that reserve memory at once, as runtime flags describes. A large observed state costs on every request whatever the guest is.
Measurements
The figures below were measured on 2026-08-16 on linux/arm64, on the Go host with ABI v1 guests, and weren’t re-measured on the Rust host, so treat them as a rough scale.
| Go (~75 MB) | Go, raw proto (~20 MB) | Rust (~240 KB) | |
|---|---|---|---|
| one request (CPU) | 8-11 ms | 1.2 ms | 0.05 ms |
| first compile of a module | 23-28 CPU-seconds, ~1 GB peak | 6 CPU-s | 0.1 CPU-s |
| resident in memory | ~90 MB, file-backed | ~40 MB | 0.7 MB |
| per in-flight run | 11-16 MB | 4-8 MB | < 1 MB |
| on disk per module version | ~230 MB (module + artifact) | ~60 MB | 0.9 MB |
| load from a warm volume | 6-8 ms | 2 ms | 0.05 ms |
“Go” is the go scaffold and “Go, raw proto” a Go guest that uses the scaffold’s own code alone, without function-sdk-go. The full model of bounds and budgets is in the resource governance one-pager.
Install function-oci
This page is for operators installing function-oci, the runtime that runs
an OCI image as a composition function step
(design record). It covers what the package
needs from a node, its flags, and what it refuses. The Input, the policy
layers, the caches and the signatures work as they do for function-wasm:
the pages under Operators describe both packages unless they say
otherwise. The release workflow signs the package, and
Verifying a function package has the
command and the signer’s identity. The package is alpha, and
Compatibility lists what
may change between its releases.
One microVM per request
function-oci boots one microVM per request with Firecracker. The VM gets
its own guest kernel, the image’s root filesystem, immutable beneath a tmpfs
overlay, the step’s limits.memory for the process (at least 16 MiB,
held by a cgroup the init puts the process in, so the kernel’s
out-of-memory killer ends a process past it at once) plus 64 MiB for the
kernel, the init, the overlay and the page cache of the root filesystem,
and no network device. Inside it, the runtime’s init starts the image’s
configured command as the image’s configured user, the host calls the
function over gRPC, and the init relays the process’s output and exit
status to the host (the contract). The
VM ends with the run, and the next request boots a fresh one.
A step gets its response as soon as the function has answered. The
runtime stops the VM after that: the init ends the process, the runtime
logs what the process wrote last and kills the VMM. A caller doesn’t wait
for that, 19 to 24 ms on a CI runner. The run keeps its run slot
(--max-concurrent-runs) and its share of --max-total-run-memory
until the VMM has exited: both bounds count VMs. The runtime logs the lines
a process writes around its answer a moment after it returns the
response. A run the function didn’t answer ends as before: its fatal
result waits for the process’s exit and last line.
The runtime unpacks an image once per digest into a squashfs root
filesystem, which the compiled store keeps beside function-wasm’s
artifacts, under the same key and the same LRU sweep, which skips the
root filesystem of an image the runtime has in memory. The module cache’s
compile metrics time the unpacking. The runtime packs the blocks of
that file with zstd, which the guest reads faster than gzip: the published
Go example runs about 120 ms sooner for it, booted or restored
(the measurement).
Node requirements
The pod needs /dev/kvm. An unprivileged container opens the
devices its container runtime admitted into its device cgroup, no more, and a
hostPath mount of the device node doesn’t admit the device: the node appears
in the container and every open of it fails with Operation not permitted.
Kubernetes admits a device through a
device plugin:
the plugin advertises the node’s /dev/kvm as a resource and the kubelet admits
the device into the container of a pod that requests one. A plugin that
advertises any device path is
generic-device-plugin. Apply
its
manifest
with the container’s --device arguments replaced by this one:
args:
- --device
- |
name: kvm
groups:
- count: 64
paths:
- path: /dev/kvm
count is the number of pods that may use the device at once, since every one of
them shares the one /dev/kvm.
The kubelet gives the container the node’s device node unchanged, owner
and mode included, root:kvm 0660 on most node images, and the
container runs as the package’s non-root user, who isn’t in that group.
A DeploymentRuntimeConfig requests the device and puts the node’s kvm
group among the pod’s supplementalGroups:
apiVersion: pkg.crossplane.io/v1beta1
kind: DeploymentRuntimeConfig
metadata:
name: function-oci
spec:
deploymentTemplate:
spec:
selector: {}
strategy: {}
template:
spec:
securityContext:
supplementalGroups: [994]
containers:
- name: package-runtime
resources:
limits:
devic.es/kvm: "1"
Point the Function at it:
apiVersion: pkg.crossplane.io/v1
kind: Function
metadata:
name: function-oci
spec:
package: ghcr.io/jonasz-lasut/function-oci:v<version>
runtimeConfigRef:
name: function-oci
The gid is the node image’s (994 on the end-to-end suite’s kind node; images differ), so read it once per node pool, through the API alone:
kubectl debug node/<node> -it --image=busybox -- stat -c %g /host/dev/kvm
Delete the node-debugger-* pod kubectl debug leaves behind.
The pod doesn’t need privileged or any capability. A privileged
DaemonSet with the node’s /dev mounted can set the device to 0666 in
an init container instead, which is what KubeVirt does. A privileged: true function container gets every
device of the node admitted, at the cost of the boundary the pod keeps
otherwise. The end-to-end suite’s setup
runs the plugin and patches the kind node’s gid into the oci profile’s
runtime config (crates/e2e/cluster/kvm-device-plugin.yaml,
crates/e2e/profiles/oci/default/). The runtime refuses to
start without the device and says so:
cannot open /dev/kvm: No such file or directory; the OCI runtime boots a microVM per request and needs the device granted to its pod (docs/oci/install.md)
Operation not permitted in place of No such file or directory is the
hostPath mount: the node is there, the device isn’t admitted.
Permission denied is the mode: the kubelet admitted the device, and
the pod’s user is neither its owner nor in its group.
A VM’s memory comes out of the pod’s. The container’s memory limit
needs --module-memory-limit plus 64 MiB for each of
--max-concurrent-runs, and the runtime’s own use on top.
--max-total-run-memory bounds the VMs together. A VM reserves its whole
memory before it boots.
Flags
function-oci takes function-wasm’s flags
(Runtime flags) with the same defaults, and these:
| flag | env | default | what |
|---|---|---|---|
--vmm-binary-path | VMM_BINARY_PATH | /usr/lib/guestfn/firecracker | the Firecracker binary |
--guest-kernel-path | GUEST_KERNEL_PATH | /usr/lib/guestfn/vmlinux | the guest kernel, an uncompressed vmlinux |
--guest-init-path | GUEST_INIT_PATH | /usr/lib/guestfn/init | the init the runtime boots as the VM’s first process |
--vm-vcpus | VM_VCPUS | 1 | vCPUs per VM |
--enable-vm-snapshots | ENABLE_VM_SNAPSHOTS | false | restore a snapshot of the booted VM per image in place of a boot. Warm-up takes the snapshot of a --warm-modules image, and an image’s first run takes it otherwise. An alpha feature: the design record has what it does and what it measured |
The package image includes the three files. A guest kernel of your own
needs squashfs with zstd built in (CONFIG_SQUASHFS and
CONFIG_SQUASHFS_ZSTD), as the included one has: without it no VM mounts
its root filesystem, and every run fails as a guest that never connected
(Troubleshooting).
--module-stack-limit has no
meaning for a process and the runtime ignores it. --module-timeout and a
step’s limits.timeout bound the whole run, the boot included.
Refusals
- A WebAssembly artifact:
module oci … is a WebAssembly artifact, which function-oci does not serve; function-wasm serves it, or, for a manifest that declares one,… is a WebAssembly module (wasm@1.0) by its manifest, which function-oci does not serve; function-wasm serves it. Installfunction-wasmbesidefunction-ociand point the step at it. - An image for another platform:
cannot load module …: image is built for linux/arm64, and this runtime runs on linux/amd64. - An image without a command:
cannot load module …: image has neither an entrypoint nor a command: the contract runs the image's configured command (docs/one-pager-oci-runtime.md). - A manifest that requires egress:
module … requires egress (requires.egress.http), which function-oci does not serve yet: the VM has no network device (docs/one-pager-oci-runtime.md). The proxy the design record describes is a later phase. - A layer compressed with zstd:
cannot load module …: layer is compressed with zstd, which the OCI runtime does not unpack yet; build the image with gzip layers (the default).
A process that exits before answering the call, or an error from the
function, is a fatal result on the step, as a component’s error is: module … failed: process exited with status 3 before answering the call: <the last line it logged>. A process the init can’t start is module … failed: cannot start the process: <error>, and one a signal ended is module … failed: process was killed by signal 9: <the last line it logged>. The deadline and the memory limit end the run the same
way: module … failed: run failed: module exceeded its execution deadline (30s) and module … failed: process was killed: the run's memory limit of 512Mi was exceeded. When the memory limit kills a process after its answer,
the response is already the caller’s: the runtime logs the warning process was killed after it answered: the run's memory limit of 512Mi was exceeded.
A VM whose init never reaches the host before the
deadline is the runtime’s failure, not the module’s: module … failed: run failed: the guest did not connect before the deadline: the VM booted but its init never reached the host. The VM’s serial console, which --debug
logs with the run, says how far the boot got.
Try it in a kind cluster
From a checkout of the repository, on a machine with /dev/kvm:
git submodule update --init build
make e2e.up E2E_WASM=0 E2E_OCI=1
It brings up a kind cluster with Crossplane, the device plugin, a registry
and function-oci built from the checkout, installed with
make local.xpkg.deploy.function.function-oci on the runtime config
e2e-oci-default. make e2e.down removes the cluster.
On a Mac, Colima with nested virtualization
(colima start --vm-type vz --nested-virtualization) gives the kind node
the VM’s /dev/kvm, at about 5 s per run. function-oci runs on KVM
alone, and Docker Desktop doesn’t expose it.
The development loop
crossplane render works with function-oci as it does with
function-wasm (Render locally), on a Linux
machine with /dev/kvm: run the runtime with --insecure and the three VM
flags pointing at a Firecracker binary, a guest kernel and the init that
make oci.tools fetches and make oci.init builds. The loop needs a
registry, because an OCI module comes from one alone (module.type: OCI:
the runtime refuses a Path or HTTP source by name). Run a registry:3
container on 127.0.0.1:5000, then docker push the image there and
guestfn push --image the module. The runtime speaks plain HTTP to
localhost and the loopback addresses (127.0.0.1, [::1]) alone, and never
to a name that begins like one but isn’t one. A registry in a cluster needs a
certificate the pod trusts, through SSL_CERT_FILE on the function’s
container, as the end-to-end suite’s registry does
(crates/e2e/profiles/oci/default/drc.yaml). To try your own module in a
cluster, push it to a registry with a public certificate, such as GHCR.
OCI modules
This page is for authors publishing an OCI image as a module for
function-oci, the OCI runtime (design record,
the install page). It covers the contract the image’s
function follows, the manifest and the artifact
guestfn push publishes, and how the runtime runs the image. A
WebAssembly module follows Write a module instead.
The contract
An image is an ordinary Crossplane function: its command starts a
FunctionRunnerService gRPC server on port 9443, and a function built with a
Crossplane SDK doesn’t need an adapter. The runtime starts the image’s entrypoint
and command once per request, as the image’s configured user, in its
configured working directory, with its configured environment, and calls
RunFunction once the port accepts a connection.
| part | content |
|---|---|
| the request | the bytes the runtime received, unchanged |
| the response | returned unchanged. The runtime appends meta when the response leaves it out |
| a status other than OK | a fatal result with the status’s message |
| standard output and standard error | log lines. A line that parses as a JSON object with level and msg becomes a log line of that level with its other keys as fields. Any other line logs at info. The runtime attaches the module and its digest |
| the process ending before it answers | a fatal result with the exit status and the last log line |
The runtime keeps the last 256 KiB of what the process writes during a run.
When the process writes more, the runtime logs one warning with the number
of bytes it dropped from the start, then the lines it kept. The runtime
shortens a line longer than 16 KiB to that length, in the log and in a fatal
result, and marks it [truncated: N more bytes].
The server listens without TLS, since the call stays inside the VM. A
function on a Crossplane SDK demands mTLS otherwise. Its manifest sets
oci.args to ["--insecure"], a flag Crossplane’s design for functions
guarantees. The runtime resolves the step’s config.from before the run, as
for a component: input.config in the request is the configuration object
from the composite resource. The call has the run’s deadline. The
runtime sends the process no signal before it, and at the deadline it stops
the VM.
examples/function-oci-go
is function-sdk-go’s server around the hello function, with a manifest
like the one below. Its Dockerfile puts a static binary
into an empty image under a numeric user. Its Makefile has a push
target that runs the two commands of Build and publish
against a local registry.
The process runs as the image’s user, which can’t be root, with no Linux
capability in any set and no_new_privs set, so a setuid binary or a file
capability in the image grants it nothing. It sees /tmp writable and
empty, and the rest of its root filesystem through an overlay the VM
discards on exit, writable where its user may write. The init mounts both
nosuid and nodev: the kernel ignores a setuid bit and a file capability
there, and a device node in the root filesystem or under /tmp doesn’t
open a device. The devices the process can open are the ones under /dev. It sees
its own kernel, a loopback interface and no other, the host’s clock and randomness, and
the environment variables its manifest’s requires.env bindings bound.
The step credentials its manifest’s requires.credentials names travel in
the request bytes, as for a component.
The runtime unpacks the image’s layers as a container runtime does:
whiteouts remove what the layers below them left, and an entry under a
symbolic link to a directory goes where the link leads inside the image.
It leaves out the image’s device nodes, since /dev in the VM is the
kernel’s own. It keeps /.guestfn/config.json for the image config it
resolved, so an image can’t have a file there.
The manifest
contract: oci@0.1
name: tagger
version: 0.3.0
oci:
args: ["--insecure"]
requires:
credentials: [cmdb]
config:
schema:
type: object
contract: oci@0.1 names the contract and its version, and
Compatibility says what
the version means.
oci.args are the arguments for the function’s binary: they replace the
image’s command and keep its entrypoint, as a Kubernetes container’s args
do. oci.image pins the image by digest; guestfn push --image writes it, so
the file may leave it out. The other fields keep their meaning from
Module manifests. The runtime refuses
requires.egress for now: the VM has no network, and the proxy is a later
phase of the design.
Build and publish
Build the image with your own Dockerfile and push it:
docker build -t ghcr.io/acme/tagger:v0.3.0 .
docker push ghcr.io/acme/tagger:v0.3.0
# the digest: docker inspect --format '{{index .RepoDigests 0}}' ghcr.io/acme/tagger:v0.3.0
Then publish the module, the image with the manifest appended as one more layer, into the image’s repository:
guestfn push ghcr.io/acme/tagger:v0.3.0-module --image ghcr.io/acme/tagger@sha256:…
guestfn push reads guestfn.yaml and records the image’s digest in its
oci.image field. It appends a gzip tar layer holding the manifest at
/.guestfn/manifest.json to the image: the layer’s diff_id goes into
the image config and the annotation io.crossplane.guestfn: manifest onto
its descriptor, the way Crossplane’s xpkg append adds a package’s
extensions. The result is an image Docker still runs, and the command
prints the module: block for the Composition, pinned to the new digest.
Sign that digest with cosign as you sign a WebAssembly module: one
signature covers the image and the manifest. An OCI module comes from a
registry alone: the step’s module.type is OCI, and function-oci
refuses a Path or HTTP source by name.
guestfn inspect <ref> says that a module image is one and which image
the manifest records as its origin, and prints the manifest out of the
layer. For a multi-platform image it describes each platform of the index,
and guestfn manifest show <ref> prints the manifest the platforms share. function validate --resolve pulls the image and prints the contract’s verdict, as
it does for a component. From the image, --resolve needs the device:
docker run --device /dev/kvm --group-add <gid> …. A plain validate
doesn’t. A plain image, with no manifest layer, runs too,
in the default sandbox, as a bare application/wasm layer does.
Images must use gzip or uncompressed layers (every builder’s default) and
target the node’s platform. A multi-platform index resolves to the node’s.
The image’s User resolves against the image’s /etc/passwd and
/etc/group, as in a container runtime. A name missing from them is a
refusal. The runtime also refuses an image that runs as root: one that
doesn’t set User, or whose user is UID 0, by number or through its
/etc/passwd. Set a numeric USER in the Dockerfile, as the example
does.
Refusals
A refusal states the module. The common ones:
- A
PathorHTTPsource:cannot resolve module: module.type Path is not served by function-oci: an OCI module is an image pulled from a registry, so module.type must be OCI. Push the image to a registry; the development loop uses a local one (Install function-oci). image has neither an entrypoint nor a command: setENTRYPOINTorCMDin theDockerfile.image runs as root: set a non-rootUSERin theDockerfile.image is built for linux/arm64, and this runtime runs on linux/amd64: build for the node’s platform, or push a multi-platform index.image unpacks to more than 1073741824 bytes, eight times the size limit (--module-size-limit): the layers unpack to more than eight times the runtime’s--module-size-limitbetween them. Build a smaller image, or have the operator raise the flag.image holds more than 1000000 entries, the most the OCI runtime unpacks: the layers contain more than a million files, directories and links between them. Build a smaller image.layer entry .guestfn/config.json is at /.guestfn/config.json, which the OCI runtime keeps for the image config it resolved: remove the file from the image.layer entry <path> has a .. segment, which could name a path outside the image, orlayer entry <path> is under <parent>, which is not a directory: a layer doesn’t unpack into a root filesystem. Rebuild the image with a builder that writes ordinary layers.process exited with status 1 before answering the call: <line>: the process ended before it answered. The line is the last one it logged. An SDK server without--insecureends this way: check the manifest’soci.args.run returned an error: <message> (gRPC status <code>): the function answered the call with an error.run failed: module exceeded its execution deadline (30s): the step’slimits.timeoutor the runtime’s--module-timeoutbounds the run, boot included.run failed: the guest did not connect before the deadline: the VM booted but its init never reached the host: the process never started; the runtime’s--debuglog has the VM’s console, which says where the boot stopped. Not the module’s doing.
Install function-oci lists the rest.
Module manifests
This page is for module authors deciding what to put in guestfn.yaml. It
covers its contents, how the runtime checks it, the refusals you can expect
and the composes declaration. It assumes a scaffolded project
(Write a module); what each policy layer permits is in
the Cedar policy reference.
Manifest contents
guestfn init writes a guestfn.yaml like this one (the Go scaffold’s):
# The module manifest: what this module declares about itself. guestfn build
# validates it, guestfn push publishes it beside the module as the artifact's
# manifest layer, and the runtime holds it against what the policy layers grant
# before every run - a manifest can refuse a run earlier and say why, never
# make one possible.
contract: wasm@1.0
name: my-fn
version: 0.1.0
# requires: the sandbox capabilities the module cannot run without
# (egress.http rules, filesystem.privateTmp, env credential bindings),
# granted where the compositionPolicy and the operator's Cedar policy permit. This guest fetches a
# greeting only when config.greetingUrl is set, so it requires nothing and
# renders without any grant.
config:
# The JSON Schema (draft 2020-12) of the Input's config; the runtime refuses
# a request whose config does not match, naming the field.
schema:
type: object
properties:
greeting: {type: string}
greetingUrl: {type: string, format: uri}
additionalProperties: false
The fields:
-
contract: the contract the module follows, as<engine>@<major>.<minor>. Required.wasm@1.0is the component world of a WebAssembly module, whichfunction-wasmserves;oci@0.1the contract of an OCI image, which the OCI runtime serves (OCI modules). From a contract’s 1.0 a minor adds what a module may use and a major changes what the engine does with a module, and at 0.x a minor may change anything. The runtime refuses a version its engine doesn’t offer. The field wasabi, an integer, through 0.6, and the old name is refused as unknown. -
oci: what anoci@0.1module alone says.oci.imageis the digest-pinned reference of the image it runs (ghcr.io/acme/tagger@sha256:…), whichguestfn push --imagewrites into the published manifest, so the file may leave it out.oci.argsare the arguments for the function’s binary, replacing the image’s command and keeping its entrypoint. A function on a Crossplane SDK needs["--insecure"]. Awasm@1.0manifest has nooci, and the runtime refuses one that sets it. -
name,version,descriptionandsource: what the module says about itself. -
requires: the sandbox capabilities the module can’t run without. These are egress rules (egress.http),filesystem.privateTmp,envcredential bindings and the stepcredentialsthe module reads whole from its request. The runtime reads the manifest with a YAML 1.2 parser written in Rust. Unquotedyes,no,onandoffare booleans, an unquoted0755or1_000parses as755and1000, a merge key (<<: *anchor) merges, and.infand.nanare refused. Quote a value that must stay a string.function validatereads a Composition file the same way. -
config.schema: a JSON Schema (draft 2020-12) for the Input’sconfig. It must be self-contained: the runtime refuses a$refto a URL or a file at load.patterntakes theregexcrate’s syntax, which has no look-around and no back-references. Non-secret configuration belongs inconfig, not in env. -
composes: what the module writes, advisory (below). -
requires.resources: what the module asks Crossplane for, advisory (below).
guestfn push publishes the file as a second layer of the OCI artifact, with
the media type application/vnd.guestfn.manifest.v1+json. The layer is covered
by the manifest digest the Composition pins, and so by any cosign signature on
it.
For an oci@0.1 manifest, guestfn push <ref> --image <image@sha256:…>
appends the file to the image instead, as one more layer. The layer is a
gzip tar holding /.guestfn/manifest.json, with its diff_id in the
image config and its descriptor annotated io.crossplane.guestfn: manifest, and the result goes into the image’s repository under the
reference given. The image is built and pushed by its own toolchain first
and remains runnable afterward. The Composition pins the result, a
signature covers image and manifest together, and the runtime reads the
manifest out of that one layer before it pulls the rest. guestfn inspect
says that a module image is one. function-wasm refuses it by name, since
the package for the OCI runtime serves it.
A path or http source has no OCI manifest layer. It can reference its
guestfn.yaml instead, with module.manifestPath or module.http.manifestURL
and manifestDigest (Input reference). A
module with no manifest runs in the default sandbox: nothing but the request,
and no step credential.
Policy check and refusals
A manifest is a request. After the module loads, the runtime checks each
requires entry against the Input’s compositionPolicy and the operator’s
--sandbox-policy-file, and a capability is granted when both permit
it and in no other case. The manifest can make a run fail earlier, with a message saying why. It
can’t make a run possible or widen a grant.
A required capability that a layer doesn’t permit is a fatal result before the module runs:
module oci ghcr.io/example/greeter@sha256:… requires egress GET to host "api.example.com" (requires.egress.http[0]), which the operator policy (--sandbox-policy-file) does not permit
… requires a private /tmp (requires.filesystem.privateTmp), which the compositionPolicy does not permit for this request
… requires credential "cmdb" (requires.credentials[0]), which the operator policy (--sandbox-policy-file) does not permit
A config that doesn’t match the schema fails the same way, and a schema
that reaches outside itself
is refused when the manifest is read:
… config does not match the module's schema: /greeting: got number, want string
… has an invalid manifest: config.schema: Resource 'http://example.com/schema.json' is not present in a registry and retrieving it failed: $ref http://example.com/schema.json is external; config.schema must be self-contained
guestfn push prints the requires: block under the module: block. A
Composition author reads it to see what the layers must permit.
guestfn inspect <ref> shows what a published module requires, and
function validate --resolve applies the same checks offline.
The composes declaration
A manifest can declare what the module writes, beside what it needs:
composes:
- kind: policy/PodDisruptionBudget # <group>/<Kind>, the core group spelled core
changes: [add] # add, modify, remove; all three when omitted
The declaration is for tooling. The policy layers fence a module’s output
with composeResource rules, judged over the actual response after the run
(the output fence), and the
runtime doesn’t read composes.
The tooling reads it in three places:
function validate --resolvewarns where the step’scompositionPolicyor the operator policy would refuse a declared kind and change, such asthe module declares it composes policy/PodDisruptionBudget (add), which the compositionPolicy does not permit (composeResource).guestfn inspectshows it in the manifest summary.guestfn scaffold compositionwrites the matchingcomposeResourcepermits into thecompositionPolicyskeleton it derives fromrequires.
guestfn build refuses an unknown field inside composes, which catches a
typo in the file you’re editing. Parsing a published manifest doesn’t check
composes for unknown fields. The runtime ignores them.
The requires.resources declaration
A manifest can declare what the module asks Crossplane for through its
response’s requirements, under requires beside the capabilities:
requires:
resources:
- kind: apiextensions.crossplane.io/EnvironmentConfig # <group>/<Kind>, the core group spelled core
by: [name] # name, labels; both when omitted
The declaration is for tooling, and unlike the other requires entries it’s
never granted or refused before the run. The policy layers fence a module’s
reads with requireResource rules, judged over the actual selectors after the
run (the read fence), and the
runtime doesn’t read requires.resources. The tooling reads it in the same
three places:
function validate --resolvewarns where a layer would refuse a declared kind, such asthe module declares it requires core/Secret (by name), which the compositionPolicy does not permit (requireResource). It judges a read by name with an empty name and a read by labels with no labels, and never with a namespace, so a rule conditioned on a value may warn for a selector the run would permit.guestfn inspectshows it in the manifest summary.guestfn scaffold compositionwrites the matchingrequireResourcepermits, withcontext has nameorcontext has labelsfromby.
guestfn build refuses a kind that isn’t <group>/<Kind>, a by entry
other than name and labels, and an unknown field inside an entry, as it
does for the rest of requires.
Check a composition
This page is for module authors and composition authors who want to know,
before the first reconcile, whether the runtime admits a Composition’s
function-wasm steps. It covers function validate, the validate subcommand of
the runtime binary. It doesn’t run a module.
Crossplane never installs a function’s Input CRD, so the runtime is the one
gate an Input passes. function validate
runs that gate offline. It applies the same checks to every function-wasm step
of the Compositions (or bare Input documents) you give it.
It takes the same flags as the serving runtime, such as --module-timeout,
--module-memory-limit, --sandbox-policy-file and --cosign-key. Pass the
flags your pod runs with, or the verdict can differ from the cluster’s.
cargo run --release -p function-wasm -- validate \
example/composition.yaml --module-dir=. --resolve
# or, with the released image (its entrypoint is the runtime):
docker run --rm -v "$PWD:/w" ghcr.io/jonasz-lasut/function-wasm:<version> validate /w/composition.yaml \
--sandbox-policy-file /w/policy.cedar
Each step prints one line, with its warnings indented below. A step checked through --resolve also prints the module’s digest and what its request contains. These lines come from the conformance fixtures, so their paths aren’t a real project’s:
testdata/validate/credentials.yaml: Composition/credentials pipeline[1] permitted: OK (path fn.wasm, compositionPolicy)
module: sha256:09e6ac0cbcc0abcea78afa7df96114b5e4c3bf4020eb97a9aa188e17473d9714, 255 B, contract wasm@1.0; manifest: cmdb-reader 0.1.0, credentials cmdb
credentials: cmdb
testdata/validate/credentials.yaml: Composition/credentials pipeline[2] fenced: refused: module module file fn.wasm requires credential "cmdb" (requires.credentials[0]), which the compositionPolicy does not permit
The refusal is the runtime’s own sentence, so a message you find here is the one the pod logs. Troubleshooting explains each.
Flags
By default validate checks the Input alone: the compositionPolicy compiles, limits stay within the ceilings, and the module source is well formed. These flags change the check or its output.
--resolveresolves and fetches each module. It checks the signature against--cosign-keyand compiles the module with Wasmtime for the runtime’s own verdict on size, ABI and host imports. It then decides the manifest’srequiresas the runtime does, and lists on acredentials:line the step credentials the module’s request would contain. With none listed, the module receives none. OCI pulls use the local Docker config and never a step credential. When the module’s manifest declares a kind incomposesthat a policy layer would refuse, the step gets a warning such asthe module declares it composes core/Secret (add), which the compositionPolicy does not permit (composeResource).--xr xr.yamlmaterializesmodule.fromsources against that composite resource, as the observed XR would. Without it, afromsource is checked for thecompositionPolicyit requires and nothing else, and a field the XR leaves unset undermodule.allowEmptyis reported as no module.--function-namekeeps the steps of one function and drops the rest.--output jsonprints one JSON object per step, one per line, for CI annotations.-reads stdin.
A step whose compositionPolicy scopes composeResource or requireResource ends its OK line’s parenthesis with the action, as in OK (path fn.wasm, compositionPolicy, composeResource). The policy fences the module’s output or its reads, which a run alone can judge, so validate reports the scoping and not a verdict.
Warnings and exit codes
Warnings never change the exit code. The runtime warns about:
- A
Pathsource in a Composition:module.type Path names a file under the runtime's --module-dir and carries no digest; a cluster Composition should pin an OCI or HTTP source by digest - A module that requires egress when the runtime can’t verify signatures, under
--resolve:the module requires egress but is not signature-verified: neither --cosign-key nor --cosign-trusted-root was given - A limit equal to its ceiling:
limits.timeout <value> equals --module-timeout: it narrows nothing, and the same forlimits.memoryagainst--module-memory-limit - A field the runtime ignores:
unknown field "<name>" is ignored by the runtime
The exit code is:
- 0 when every step is admitted.
- 1 when at least one step is refused.
- 2 when the tool itself failed: an unreadable file, unparsable YAML or a bad flag.
To run it as part of the development loop, see Render locally.
Input reference
This page is for composition authors writing a function-wasm step and for
operators who need to predict what the runtime admits. It lists every field
of the step’s Input and what the runtime enforces for each. Crossplane never
installs the Input’s CRD. The runtime enforces it alone and checks
every rule on every request, and function validate applies the same checks
offline. The CRD under package/wasm/input/ is for tooling and IDEs alone, and
the runtime generates it from its own types.
The Input is apiVersion: guestfn.crossplane.io/v1, kind: Input. A step
that still says wasm.fn.crossplane.io/v1 or v1beta1, the group of 0.6
and earlier with the same fields, is refused with a sentence that states
the new group (Compatibility).
module: # required
type: OCI # required: OCI | HTTP | Path - the Composition's choice
oci: {ref, credentials} # exactly one of the object matching type …
http: {url, digest}
path: fn.wasm
from: status.module # … or the observed XR field holding it
allowEmpty: true # optional, with from: an unset field runs nothing
compositionPolicy: | # optional; the composition author's own Cedar layer
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example-org");
limits: # optional; each at most the runtime's ceiling
timeout: 5s
memory: 128Mi
config: # optional; the module's configuration, read from the XR
from: spec.config # the observed XR field holding it, an object
allowEmpty: true # optional: an unset field runs the module unconfigured
Everything but the source and the configuration is read from the Input:
compositionPolicy and limits are the Composition’s, never the composite
resource’s. The Input
has no sandbox block. Capabilities come from the module’s manifest and
two Cedar layers, described under Capabilities.
The fields are:
| field | type | description |
|---|---|---|
module | object | Required. Where the module comes from |
module.type | string | Required. OCI, HTTP or Path. One of the object it names (oci, http, path) or module.from is set, not both, and no object of another type may be present. With function-oci the type is OCI alone: an OCI module is an image pulled from a registry, never a file or a URL |
module.oci.ref | string | OCI artifact reference pinned to its manifest digest, registry/repo@sha256:…, as guestfn push prints it. See OCI references |
module.oci.credentials | string | name of the pipeline-step credential used to pull. See Pull credentials |
module.http.url | string | the HTTP or HTTPS URL the module is downloaded from. See HTTP redirects |
module.http.digest | string | Required. sha256:<hex> of the module, which the runtime verifies the download against. A digest the runtime already caches is served without a download |
module.http.manifestURL | string | Optional. A guestfn.yaml served beside the module. Set with module.http.manifestDigest. Without it an HTTP source has no manifest and gets the default sandbox alone. For a module.from http source, compositionPolicy pullModule fences it like the module URL |
module.http.manifestDigest | string | sha256:<hex> of the manifest, verified against it. Required with module.http.manifestURL, refused without it |
module.path | string | a file relative to the runtime’s --module-dir. Refused unless that flag is set. A Path source has no digest |
module.manifestPath | string | Optional, for type: Path alone. A guestfn.yaml under --module-dir, the manifest of a local or volume-mounted module. Never set through module.from, and re-read on each request. A local edit takes effect without a restart |
module.from | string | a field of the observed composite resource, under spec. or status., that holds the source. See Modules chosen by the XR |
module.allowEmpty | boolean | Optional, with module.from alone. See Skipping a step |
compositionPolicy | string | the composition author’s Cedar layer. See The composition policy |
limits.timeout | duration | time budget of one run, e.g. 5s. See Limits |
limits.memory | quantity | memory a run may use, its linear memories and tables together, e.g. 128Mi. See Limits |
limits.concurrency | int32 | at most N runs of this step at once. See Limits |
config | object | Optional. Where the module’s configuration comes from. See Configuration from the XR |
config.from | string | Required within config. A field of the observed composite resource, under spec. or status., that holds the configuration as an object |
config.allowEmpty | boolean | Optional, with config.from. An unset field (absent or null) runs the module unconfigured instead of a fatal result |
HTTP redirects
A download of module.http.url or module.http.manifestURL follows up to ten
redirects. A redirect within the origin of the URL, which is its scheme, host
and port, is followed unchanged. A redirect to another host is refused unless that host resolves to an address
outside the
default block list. The runtime
connects to it directly, without a proxy. A release asset that redirects to a
public download host works. For a module behind a redirect to an address
inside the cluster, specify the final URL in the Input instead.
OCI references
module.oci.ref must include a manifest digest. A tag alone is refused, and
the runtime doesn’t resolve tags at request time. With
registry/repo:tag@sha256:… the digest alone is fetched. The manifest states
its layer’s digest, and the runtime verifies both on fetch.
The runtime reads the registry part into one canonical form, and the
policies, the signature check and every message use that form. The host is
lowercase and has no trailing dot. The default port goes, so ghcr.io:443 is
ghcr.io, and any other port stays. Docker Hub is index.docker.io, also when
the reference says docker.io. The runtime refuses a registry part with user
information, or one that isn’t a host name or an IP address with an optional
port. The canonical registry has
the rules.
The runtime takes the first layer whose media type is application/wasm,
application/vnd.wasm.content.layer.v1+wasm or
application/vnd.module.wasm.content.layer.v1+wasm. Failing that, it takes
the one layer that isn’t the manifest layer. A tar layer (a FROM scratch
image) must hold the module at /fn.wasm.
Pull credentials
module.oci.credentials names a pipeline-step credential: a Secret with
.dockerconfigjson, or with username and password keys. It’s declared
on the step:
- step: greet
functionRef:
name: function-wasm
credentials:
- name: registry
source: Secret
secretRef:
namespace: crossplane-system
name: ghcr-pull
input:
apiVersion: guestfn.crossplane.io/v1
kind: Input
module:
type: OCI
oci:
ref: ghcr.io/example/private-fn@sha256:…
credentials: registry
Without credentials, the runtime tries its Docker config (DOCKER_CONFIG),
then anonymous access. The module never receives the pull credential, and a
manifest that names it as an env binding source or a required credential is
refused.
Modules chosen by the XR
With module.from, each composite resource chooses its module. The
Composition states the type and the XR field, and the field contains the source:
an object {ref, credentials} for OCI, {url, digest} for HTTP, a
string for Path. The runtime reads it on every request and rejects unknown fields. A typo or a wrong structure is a fatal result that states the
field. An unset field is a fatal result naming it, unless module.allowEmpty
says otherwise.
input:
apiVersion: guestfn.crossplane.io/v1
kind: Input
module:
type: OCI
from: spec.module # spec.module: {ref: ghcr.io/example-org/greeter@sha256:…}
compositionPolicy: |
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example-org");
A source chosen this way is fenced by the compositionPolicy, which is
required for OCI and HTTP sources. See
The composition policy.
Skipping a step
module.allowEmpty: true lets the composite resource leave the field unset
(absent, or null). The step then runs nothing and returns the request’s
desired state and context unchanged. The pipeline continues. A set field
is handled as any static source is. The Input alone decides this, so an XR
can leave a step empty where the Composition allows it and nowhere else, and
allowEmpty without module.from is refused. The runtime logs a skipped
step and counts it as requests_total{outcome="skipped"}.
Spending the pull credential
An XR-chosen module may specify a pull credential where the
compositionPolicy permits spendCredential for it and for a
repository that a pullModule permit admits, and in no other case. The pull check runs first. The
spendCredential rule tests context has repository, because the context
carries repository for this pull credential alone:
module:
type: OCI
from: status.module # status.module: {ref: ghcr.io/example-org/…@sha256:…, credentials: registry}
compositionPolicy: |
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example-org");
permit (principal, action == Action::"spendCredential",
resource == Credential::"registry")
when { context has repository &&
context.repository in Repository::"ghcr.io/example-org" };
Configuration from the XR
The module’s configuration is a field of the composite resource, which the
step names in config.from. The module’s author publishes its structure as
the manifest’s config.schema; the composite resource definition declares
the field, with that schema transplanted, so the API server checks and
defaults the values; the runtime reads the field on every request, holds it
against the manifest’s schema as the backstop and hands it to the module as
input.config, where every guest reads its configuration. A module chosen
through module.from is configured by the same author who chose it, and a
fixed module exposes what the definition declares. Secrets don’t belong
there: a module reads a step credential through its manifest’s
requires.env or requires.credentials.
input:
apiVersion: guestfn.crossplane.io/v1
kind: Input
module:
type: OCI
from: spec.addOn
config:
from: spec.addOnConfig # spec.addOnConfig: {maxUnavailable: 2}
allowEmpty: true # a WebApp that sets none runs the add-on unconfigured
The field’s value must be an object. A step without config runs the
module unconfigured. A value written under config itself, as 0.6 took it, is
refused at admission with a sentence that states where it belongs:
config.greeting is not a field of config, which has from and allowEmpty only: the module's configuration is written in the composite resource, in the field config.from names
A request without an observed composite resource, a field the resource
doesn’t have or a value that isn’t an object is a fatal result worded as
module.from’s:
config.from spec.addOnConfig: no observed composite resource to read it from
config.from: cannot read spec.addOnConfig from the composite resource: addOnConfig: no such field
config.from: spec.addOnConfig of the composite resource is not an object
config.allowEmpty: true makes an unset field (absent or null) run the
module unconfigured, the state of a step without config; a scalar or a
list is refused either way. function validate --xr reads the field from the
composite resource given and prints the same sentences; without --xr it
reports the reference and leaves the value unchecked.
The composition policy
compositionPolicy is Cedar text. Malformed Cedar is a fatal result at admission. It’s required whenever
module.from names an OCI or HTTP source: without it the XR author could
point the runtime at any host.
For a module.from source, a pullModule permit must match the module’s
normalized location, and a step credential may be spent where a
spendCredential permit matches and nowhere else. For sandbox actions the layer can
narrow what the manifest and the operator grant, never widen it. The actions, entities,
evaluation rules and refusal sentences are in the
Cedar policy reference.
Limits
limits narrow what the runtime allows and never widen it.
limits:
timeout: 5s # ≤ --module-timeout
memory: 128Mi # ≤ --module-memory-limit
limits.timeoutis at most--module-timeout, otherwise a fatal result states both:limits.timeout 1m0s exceeds the runtime's --module-timeout of 30s. The runtime measures the budget in wall-clock time, and a guest that sleeps or blocks in a WASI call spends it as one that computes does. Time spent waiting on the host’s HTTP answers is credited back (see HTTP egress), and the request’s own gRPC deadline still caps the run if shorter.limits.memoryis at most--module-memory-limit, otherwise a fatal result states both:limits.memory 1Gi exceeds the runtime's --module-memory-limit of 512Mi.limits.concurrencycaps runs of this step at once, across all requests, keyed by the module’s content digest. A further request waits under its own deadline. If the deadline passes first, the result is fatal and isn’t counted as a run. A value over--max-concurrent-runsis capped to it without an error.
Capabilities
A module declares the capabilities it can’t run without in its manifest, as
requires (Module manifests). The runtime
grants each one on the condition that the Input’s compositionPolicy and the operator’s
--sandbox-policy-file both permit it
(three-layer authorization). The same
two layers may fence what the module composes with composeResource and what
it asks Crossplane for with requireResource: see the
output fence and the
read fence. Egress is covered on
HTTP egress.
Step credentials
Of the step’s credentials, the request a module receives contains no credential but those
its manifest names and both policy layers permit with spendCredential: the
credential a requires.env binding reads, or one it reads whole with
requires.credentials. The runtime edits every other credential out before
the module runs, so a module with no manifest sees none.
A required credential that the step doesn’t declare is a fatal result before
the run: … requires.credentials[0]: the request carries no credential "cmdb"; declare it on the pipeline step.
Private /tmp and environment
The private /tmp needs usePrivateTmp permitted in both Cedar layers. An
env binding needs setEnv and spendCredential in both. A required
capability that either layer doesn’t permit, or any on a runtime with no
--sandbox-policy-file, is a fatal result before the module runs. The
manifest syntax is on Module manifests.
Runtime flags
This page is for operators who run the function-wasm runtime from a Crossplane package and set its flags through a DeploymentRuntimeConfig. It lists each flag with its environment variable and default, one line each. The linked pages have the detail.
The binary has two subcommands, serve and validate. serve is the default, so function --insecure --module-dir=. and a DeploymentRuntimeConfig’s args don’t name it. validate takes the flags marked “yes” in the validate column below, with the same defaults and environment variables, so it checks a Composition against what a runtime started with those flags would admit.
Limits and sources
These flags set the ceilings that a step’s limits can’t exceed (Input reference) and where path sources come from.
| flag | env | default | validate | purpose |
|---|---|---|---|---|
--module-dir | MODULE_DIR | unset | yes | directory served for path sources; unset refuses them |
--module-size-limit | MODULE_SIZE_LIMIT | 128 MB | yes | largest module accepted; an image’s layers may unpack to eight times it on function-oci |
--module-timeout | MODULE_TIMEOUT | 30s | yes | wall-clock budget of one run, and the ceiling for limits.timeout |
--module-memory-limit | MODULE_MEMORY_LIMIT | 512 MB | yes | memory one run may use: its linear memories and tables (a host pointer per element) together, the initial memory included; also the ceiling for limits.memory |
--module-stack-limit | MODULE_STACK_LIMIT | 512 KB | no | call stack one run may use. Past it the run fails with trap: call stack exhausted. No Input field narrows it |
--ttl | TTL | 60s | no | TTL of responses the runtime itself produces (fatal results); a module sets its own |
Concurrency
By default nothing is bounded: concurrency is the caller’s, set by Crossplane’s reconcile workers.
| flag | env | default | validate | purpose |
|---|---|---|---|---|
--max-concurrent-runs | MAX_CONCURRENT_RUNS | 0 (unbounded) | no | module runs executing at once; a request that can’t get a slot before its deadline is a fatal result (waiting for a run slot: deadline exceeded) and never ran |
--max-total-run-memory | MAX_TOTAL_RUN_MEMORY | 0 (unbounded) | no | total memory budget in MB across running modules, linear memories and tables together; see below |
--max-concurrent-compiles | MAX_CONCURRENT_COMPILES | 1 | no | modules compiled at once; a compile is heavy on CPU and memory, so further first requests wait their turn |
--module-compile-timeout | MODULE_COMPILE_TIMEOUT | 0s (unbounded) | no | wall-clock bound on a cold load, the fetch and compile of a module that isn’t cached yet. Past it the request fails with cannot load module …: compile exceeded --module-compile-timeout <duration>; the compile runs to its end, keeps its compile slot until then and stores its artifact for the next request. The syntax of --module-timeout |
A component reserves nothing up front. The runtime charges each memory or table growth, the initial memory included, to the --max-total-run-memory pool as the guest claims it, and a run waits under its deadline while the pool is full. A growth the pool can’t serve before the deadline fails inside the guest as a failed memory.grow, counted in guestfn_module_memory_denials_total. See Sizing for what these bounds cost.
Caches
Compiled modules are cached in memory, and fetched modules and compiled artifacts on disk. See Cache storage for the directory.
| flag | env | default | validate | purpose |
|---|---|---|---|---|
--enable-memory-cache | ENABLE_MEMORY_CACHE | true | no | keep compiled modules in memory between requests; the flag takes a value, and with --enable-memory-cache=false each request maps the compiled artifact from disk and releases it afterward |
--max-cached-modules | MAX_CACHED_MODULES | 0 (unbounded) | no | most compiled modules resident at once; past it the module idle longest is dropped, freed once its last run ends |
--max-cache-size | MAX_CACHE_SIZE | 0 (unbounded) | no | MB the two on-disk caches may hold together; past it the runtime removes the entries unused for longest, at startup and every ten minutes. function-oci keeps the root filesystem of an image for as long as the image is in memory, whatever the bound. Size the volume, or set this below its size |
--warm-modules | WARM_MODULES | unset | no | modules loaded before readiness; see Readiness and warm-up |
Signing
These flags set which module signatures the runtime accepts. Signatures explains each mode and how they combine.
| flag | env | default | validate | purpose |
|---|---|---|---|---|
--cosign-key | COSIGN_KEY | unset | yes | PEM file of cosign public keys for key-based cosign 3 signatures |
--cosign-trusted-root | COSIGN_TRUSTED_ROOT | unset | yes | Sigstore trusted_root.json that verifies keyless signatures offline; excludes --cosign-trust-instance |
--cosign-trust-instance | COSIGN_TRUST_INSTANCE | unset | yes | public-good, staging or github: fetch that instance’s trusted root over TUF and refresh it while serving |
--cosign-tuf-refresh | COSIGN_TUF_REFRESH | 1h | no | how often --cosign-trust-instance refreshes the root, at least 1m |
Policy and egress
See Operator grant policy for writing and mounting the policy and HTTP egress for the egress budgets.
| flag | env | default | validate | purpose |
|---|---|---|---|---|
--sandbox-policy-file | SANDBOX_POLICY_FILE | unset | yes | Cedar document holding the operator’s grant policy; unset, every sandbox capability is refused. Compiled once at startup: restart to reload |
--egress-rate-limit-per-minute | EGRESS_RATE_LIMIT_PER_MINUTE | 0 (off) | yes | sustained egress requests per minute per module digest, as a process-wide token bucket |
--egress-rate-limit-burst | EGRESS_RATE_LIMIT_BURST | 0 (derived) | yes | burst tokens for the rate limit; 0 derives max(1, requestsPerMinute) |
Health and metrics
Both endpoints are plain HTTP, because the function port speaks mTLS. Readiness and warm-up covers wiring probes.
| flag | env | default | validate | purpose |
|---|---|---|---|---|
--health-address | HEALTH_ADDRESS | :8081 | no | /livez and /readyz (503 while warming); empty disables them |
--metrics-address | METRICS_ADDRESS | :8080 | no | Prometheus /metrics (Metrics); empty disables it |
The SDK’s flags --insecure, --debug, --tls-certs-dir, --address and --max-recv-message-size apply too.
Logging
--debug turns on the runtime’s own debug lines in a human-readable format: guest log records sent at debug level, the credentials withheld from a module and trap details. Everything else logs at info, so a compile under --debug doesn’t print per-pass lines from the compiler. A set RUST_LOG replaces the flag’s filter in full.
Cache storage
The caches live under /tmp/guestfn-cache, which isn’t configurable. Mount an emptyDir there if the pod’s root filesystem can’t be written, or a volume to keep the fetched modules and manifests across pod restarts:
spec:
deploymentTemplate:
spec:
template:
spec:
containers:
- name: package-runtime
volumeMounts:
- name: cache
mountPath: /tmp/guestfn-cache
volumes:
- name: cache
persistentVolumeClaim:
claimName: guestfn-cache
A volume keeps the fetched modules and the manifests, which the runtime verifies against their digest on every read. It doesn’t keep the compiled code. Each process signs the artifacts it writes under a key drawn at startup and refuses every other (trust model). A restarted pod compiles its modules again. Pods must not share a volume, because each would refuse and overwrite the other’s artifacts. Give each pod its own volume, with no writer but the runtime. The runtime removes the compiled directories of other Wasmtime versions after a day without writes.
Opening the sandbox
Mount the Cedar --sandbox-policy-file through the same DeploymentRuntimeConfig, and put a tmpfs behind TMPDIR to bound the private /tmp:
spec:
deploymentTemplate:
spec:
template:
spec:
containers:
- name: package-runtime
args:
- --sandbox-policy-file=/etc/guestfn/policy.cedar
env:
- name: TMPDIR
value: /scratch
volumeMounts:
- {name: policy, mountPath: /etc/guestfn, readOnly: true}
- {name: scratch, mountPath: /scratch}
volumes:
- name: policy
configMap: {name: function-wasm-policy}
- name: scratch
emptyDir: {medium: Memory, sizeLimit: 64Mi}
A fuller example with every operator-authorable option is examples/deployment-runtime-config-cedar.yaml.
Operator grant policy
This page is for operators of function-wasm. It shows how to write the Cedar
policy that --sandbox-policy-file loads, mount it into the function’s pod and
check it offline with function validate. It covers the operator layer alone:
the schema and how each layer decides are in the
Cedar policy reference.
The policy file alone enables a sandbox capability. A module’s manifest requests a capability and the Input’s compositionPolicy can narrow it, but neither can grant more than the operator’s policy does.
Evaluation is default-deny: a capability is refused unless a permit matches it, and a forbid overrides a permit. Without a --sandbox-policy-file, no capability is grantable and every module runs in the default sandbox, which has nothing but the request. A file that permits one capability still refuses every other one, so permit each capability you mean to allow.
Actions and principal
The capability actions are:
usePrivateTmp: a private/tmp.setEnv: environment variables bound to step credentials.spendCredential: the step credentials a module reads.grantEgress: HTTP egress, which is also the host allowlist.
The operator layer also decides dialAddress, on the egress page, and requireSignature and trustSigner on signatures. composeResource and requireResource, below, fence a module’s output and its reads rather than granting a capability.
The principal’s attributes, and the resources and context of each action, are in the Cedar policy reference.
Write the policy
This policy lets team-a alone use a private /tmp, and lets any
namespace reach *.example.com with GET:
permit (principal, action == Action::"usePrivateTmp", resource)
when { principal.namespace == "team-a" };
permit (principal, action == Action::"grantEgress", resource)
when { resource in HostPattern::"example.com" && context.method == "GET" };
Mount it and set the flag
Put the policy in a ConfigMap in the namespace the Function runs in (here crossplane-system):
kubectl create configmap function-wasm-policy -n crossplane-system \
--from-file=policy.cedar
Then mount it through the Function’s DeploymentRuntimeConfig:
spec:
deploymentTemplate:
spec:
template:
spec:
containers:
- name: package-runtime
args:
- --sandbox-policy-file=/etc/guestfn/policy.cedar
volumeMounts:
- {name: policy, mountPath: /etc/guestfn, readOnly: true}
volumes:
- name: policy
configMap: {name: function-wasm-policy}
The runtime compiles the policy at startup and doesn’t reread it. After changing the ConfigMap, restart the function’s pod.
Check it offline
function validate reports the same verdicts as the runtime, without a cluster:
function validate composition.yaml --resolve \
--sandbox-policy-file policy.cedar --xr xr.yaml
The principal comes from --xr. Without it, the zero principal matches no per-tenant condition. The command and its other flags are in Check a composition.
Fence what modules compose
composeResource isn’t a capability. It’s a ceiling on what any module may compose, judged over the response after the run. It applies where a rule scopes it and nowhere else. Otherwise every module’s output is applied unchanged.
A forbid that specifies the action scopes it and permits nothing. A ceiling written that way needs a permit beside it. A forbid with an unconstrained action, forbid (principal, action, resource) when { … };, needs none: the layer refuses what it matches and permits the rest (Cedar policy reference). This policy refuses RBAC resources and Secrets and permits everything else:
forbid (principal, action == Action::"composeResource", resource)
when { resource in Group::"rbac.authorization.k8s.io" || resource == Kind::"core/Secret" };
permit (principal, action == Action::"composeResource", resource);
Fence what modules read
requireResource is the same kind of ceiling over what any module may ask Crossplane for through the response’s requirements, judged over the selectors after the run. It applies where a rule scopes it and nowhere else. This policy keeps Secrets off limits, lets a module read its own namespace and opens the cluster-scoped Crossplane kinds:
forbid (principal, action == Action::"requireResource", resource)
when { resource == Kind::"core/Secret" };
permit (principal, action == Action::"requireResource", resource)
when { context has namespace && context.namespace == principal.namespace };
permit (principal, action == Action::"requireResource", resource in Group::"apiextensions.crossplane.io");
The context and the refusal sentences are on the Cedar policy reference.
Cedar policy reference
This page is for operators writing the policy file that --sandbox-policy-file
names and for composition authors writing a step’s compositionPolicy. It
assumes you know Cedar’s permit and forbid syntax and the
module manifest’s requires. Use it to write a
rule and to read the refusal it produces. Mounting the operator’s file is in the
operator grant policy, signing setup in
signatures and egress budgets in HTTP egress.
A module gets a capability beyond the default sandbox through the agreement of three layers: its manifest requests it (requires), the Input’s compositionPolicy
permits it and the operator’s policy file permits it. Both policy layers are
Cedar documents over one schema. A rule means the
same in both, and a layer can narrow what the layer before it allows and nothing more. The
trust model explains the split.
A minimal policy
With this operator policy, modules in the team-a namespace can use a private /tmp
and send GET requests to example.com and its subdomains:
permit (principal, action == Action::"usePrivateTmp", resource)
when { principal.namespace == "team-a" };
permit (principal, action == Action::"grantEgress", resource)
when { resource in HostPattern::"example.com" &&
context.method == "GET" };
A compositionPolicy is written the same way. The rest of this page defines
the names these rules use.
The layers
| layer | written by | actions it may use |
|---|---|---|
| operator policy | the operator | usePrivateTmp, setEnv, spendCredential, grantEgress, composeResource, requireResource, requireSignature, trustSigner, dialAddress |
| composition policy | the composition author | pullModule, spendCredential, usePrivateTmp, setEnv, grantEgress, composeResource, requireResource |
The runtime compiles the operator policy at startup and doesn’t reread it. A
change needs a restart. The composition policy is the Input’s
compositionPolicy string, compiled per Composition and cached by content hash.
The Input reference says where it goes in the Input and
that the runtime reads it from the Input alone, never from the composite
resource.
requireSignature, trustSigner and dialAddress are the operator’s alone:
the runtime never evaluates a compositionPolicy rule for them. pullModule is
the composition author’s alone. The operator policy has no say in where an
XR-chosen module comes from, in what it’s granted once chosen.
The principal
The runtime decides each request for the principal Request::"self", the caller
of the step. Its attributes are strings:
| attribute | value |
|---|---|
principal.namespace | the observed composite resource’s metadata.namespace |
principal.xrKind | the observed composite resource’s kind |
principal.composition | always empty: a RunFunctionRequest doesn’t include the Composition name |
A request with no observed composite resource gets the zero principal, with
every attribute empty. It matches no condition that tests one, and that’s safe
because both layers narrow and never widen. function validate builds the principal from
--xr and uses the zero principal without it.
requireSignature and trustSigner see the placeholder principal
Module::"module", which has no attributes. A rule for either that conditions
on principal never matches.
Entity types
Rules name entities in their resource scope, and in follows each type’s
hierarchy. in is reflexive: an entity is in itself.
Repositoryis a module’s location without its tag or digest. An OCI reference isregistry/repository, normalized as go-containerregistry does (docker.io/xisindex.docker.io/x), with the registry in its canonical form. For an HTTP URL, it’sscheme://host/pathwith a lowercase host and without its query. Every path-boundary prefix is an ancestor, with and without its trailing slash:ghcr.io/teamis an ancestor ofghcr.io/team/mod, andghcr.io/team-otherandghcr.io/teamsuffixaren’t.HostPatternis an egress rule’shost, in lowercase without a trailing dot, or itshostPatternas written (*.example.com). Itshostattribute is the same string, forlike. The DNS label suffixes are ancestors:api.example.comand*.example.comare bothin HostPattern::"example.com"andin HostPattern::"com".example.com.attacker.netandbadexample.comaren’t.CapabilityisprivateTmporenv.Credentialis the name of a pipeline-step credential.Kindis<group>/<Kind>of a resource a module composed, or asked Crossplane for, read from itsapiVersionandkind:apps/Deployment,policy/PodDisruptionBudget,core/Secret(the core group is spelledcore). The API version is dropped, sopolicy/v1andpolicy/v1beta1are one kind.Groupis an API group (apps,policy,core) and the parent of everyKindin it:resource in Group::"apps"is every kind of the apps group and no other.
The canonical registry
A registry has one spelling in a policy, whichever way a reference writes
it. The runtime reads the registry part of every OCI reference into its canonical
form before it builds the Repository entity, so a rule over
Repository::"ghcr.io/acme/prod" covers GHCR.IO/acme/prod/m,
ghcr.io:443/acme/prod/m and ghcr.io./acme/prod/m alike. Write the
canonical form in a rule. A rule written with another spelling wouldn’t match
any module. The runtime refuses a policy that has one.
- The host is lowercase.
- The host has no trailing dot.
- The port is absent when it’s the default of the scheme the runtime uses:
443, or80forlocalhostand the loopback addresses, which the runtime reaches over plain HTTP. Any other port is part of the name:registry.example.org:5000andregistry.example.orgare two registries. - An IPv6 address is in its shortest form, in brackets:
[::1]:5000. - Docker Hub is
index.docker.io, whether the reference saysdocker.ioorindex.docker.io, or leaves the registry out.docker.iois the one alias. The runtime doesn’t rewrite any other host:registry-1.docker.iostaysregistry-1.docker.io, and a rule overindex.docker.iodoesn’t cover it.
A single-label host keeps the port or the dot that marks it as a registry:
registry:443/team/fn stays registry:443, since registry/team/fn is a
Docker Hub repository.
The runtime refuses a registry that isn’t a host name or an IP address with
an optional port. It refuses user information (user@ghcr.io), a character
a host can’t contain, an empty label, and a shorthand IP address such as
127.1. The refusals, the logs and function validate print a module’s
canonical reference.
The runtime checks every Repository a policy names when it loads the
policy, in the scope and in the conditions, and refuses a name whose registry
part isn’t canonical:
Repository::"GHCR.IO/acme/prod" is not the canonical name of that repository; write Repository::"ghcr.io/acme/prod"
The check reads the registry part alone, so a prefix such as
Repository::"ghcr.io" or Repository::"ghcr.io/acme/" passes, and
Repository::"docker.io/library" is refused in favor of
Repository::"index.docker.io/library". A registry part that isn’t a host
is refused too:
Repository::"user@ghcr.io/acme" does not name a repository: registry "user@ghcr.io" is not a valid registry host (a host name or an IP address with an optional port, no user information)
An operator policy with such a name stops the runtime at startup, and
function validate exits with status 2, both with operator policy <file>:
before the sentence. A compositionPolicy with one is a fatal result on
every request of its step and a refusal in function validate, both with
compositionPolicy is invalid: before it. The check doesn’t read the
location of an HTTP source (scheme://host/path), and it doesn’t read a
name whose first component has no dot or port and isn’t localhost.
Actions
Each action takes one resource type and a context. The table lists them and the notes below it cover what a cell can’t:
| action | layer | resource | context | what a matching permit grants |
|---|---|---|---|---|
pullModule | composition | Repository | none | an XR-chosen source (module.from) may be fetched from that location, and an XR-chosen HTTP source’s manifestURL is fenced by the same rules |
spendCredential | both | Credential | repository, for an XR-chosen pull credential alone | the credential an env binding reads, one a module reads whole (requires.credentials) or an XR-chosen module’s pull credential |
usePrivateTmp | both | Capability::"privateTmp" | none | the private /tmp the manifest requires |
setEnv | both | Capability::"env" | keys, the set of every environment variable name the manifest binds | the env bindings as a whole |
grantEgress | both | HostPattern | method (upper case) and path (the rule’s pathPrefix, empty when it has none) | one rule’s host and method |
composeResource | both | Kind | change, name and target | nothing: it fences the module’s output |
requireResource | both | Kind | name, labels and namespace, each present when the selector sets it and absent otherwise | nothing: it fences what the module asks Crossplane for |
requireSignature | operator | Repository | none | nothing: it demands a cosign signature for modules at that location |
trustSigner | operator | Repository | issuer and identity | nothing by itself: it makes a keyless signer trusted for requireSignature |
dialAddress | operator | none | ip | nothing at request time: it adds to the egress block list |
spendCredentialhascontext.repository, the module’sRepositoryentity, for an XR-chosen OCI source’s pull credential in the composition layer alone. It’s absent for an env binding’s credential and forrequires.credentials, so test it withcontext has repository.setEnvis decided once for all bindings, andspendCredentialthen decides each binding’s credential.grantEgressis decided once per rule and per method the rule lists.composeResourceis decided once per change the module made:changeisadd,modifyorremove,nameis the composition resource name (empty for the composite resource) andtargetiscompositeorcomposed. See the output fence.requireResourceis decided once per resource selector in the response’srequirements:nameis the selector’smatchName,labelsis a record of itsmatchLabelswith the label keys as attributes (context.labels has team,context.labels["app.kubernetes.io/part-of"]), andnamespaceis the selector’s namespace. A selector matches by name or by labels, never both, and an attribute the selector doesn’t set is absent, so test it withhasfirst. See the read fence.trustSigner’sissueris the OIDC issuer of a keyless signature’s Fulcio certificate andidentityits subject alternative name, both strings for==andlike. Signatures has the precedence with--cosign-key.dialAddressmust leaveprincipalandresourceunconstrained. Itsipis the resolved address, tested withisInRange(ip("CIDR"))orisLoopback(). Aforbidadds a blocked prefix and apermita hole in the default list.
Evaluation per layer
The operator layer
The operator layer is default-deny, as Cedar evaluates it: a request is
permitted when at least one permit matches and no forbid does. A policy that
permits one capability still refuses every other capability a module requires.
With no --sandbox-policy-file nothing is grantable, and a module that requires
anything is refused with a sentence that mentions the flag.
The composition layer
The composition layer evaluates the same way, in two regimes.
The module.from fences are default-deny. A module the composite resource
chooses from an OCI or HTTP source must be permitted by a pullModule rule, and
an Input with no compositionPolicy is refused for such a source. An XR-chosen
OCI source may specify a step credential where a spendCredential rule
permits it and nowhere else, and context.repository lets one rule cover both halves. A static
source, specified in the Input, isn’t fenced.
The sandbox actions are scoped default-permit. The layer narrows usePrivateTmp,
setEnv, grantEgress and spendCredential (for env bindings and
requires.credentials) once one of its rules, permit or forbid, scopes
that action with action == Action::"setEnv" or
action in [Action::"setEnv", ...]. Until then the manifest and the operator
decide that action alone. Once scoped, a matching permit and no matching
forbid allow it. A forbid that specifies the action scopes it and permits
nothing. A ceiling written that way needs a permit beside it.
A rule with an unconstrained action behaves differently for each effect. A
permit (principal, action, resource); scopes nothing. A forbid with an
unconstrained action applies to every one of these actions and scopes none of
them: where no other rule specifies the action, the layer refuses what the
forbid matches and permits the rest. With this rule alone a module can
neither compose a Secret nor ask Crossplane for one:
forbid (principal, action, resource)
when { resource == Kind::"core/Secret" };
composeResource and requireResource follow the same rule in both layers.
They’re the two actions where the operator layer isn’t default-deny.
The runtime evaluates the composition layer first and whole. A composition
author reads their own layer’s refusal even where the operator would also deny.
A compositionPolicy that isn’t valid Cedar is refused at admission, before
anything is resolved.
The output fence
composeResource fences what a module writes. It’s default-permit in both
layers because a default-deny would have refused every module’s output on
upgrade. After the run, the runtime compares the response’s desired state with the
request’s by composition resource name and judges every change:
- A name the response has and the request didn’t is an
add. - A name both have whose resource differs is a
modify. The comparison is by value over the body, connection details and ready flag, so a guest that re-encodes a map in another order doesn’t change it. - A name the request had and the response dropped is a
remove. A response with no desired state drops everything. - A kind replaced under one name is a
removeof the old kind and anaddof the new one.
The composite resource’s own desired state is judged as
Kind::"<xr group>/<xrKind>" with context.target == "composite" and an empty
name. A status write is a modify.
Every layer that scopes the action must permit each change. A refusal is a fatal result that states the module, the kind, the name, the change and the layer, and none of the module’s output is applied. The runtime doesn’t judge a response that already contains a fatal result.
The fence judges the desired state. What a module asks Crossplane for is
judged by the read fence. A module can also write context
and conditions, which neither fence sees.
The read fence
requireResource fences what a module asks Crossplane for. Through the
response’s requirements a module can request any resource the Function’s RBAC
lets Crossplane read, and Crossplane returns it in the next request’s
required_resources. After the run, the runtime judges every
ResourceSelector in requirements.resources and in the deprecated
requirements.extra_resources, in key order with the current map first, as
Kind::"<group>/<Kind>" with the selector’s name, labels and namespace
in the context where the selector sets them. The runtime judges the ask, since
the ask is what it sees. Crossplane reads the resources after the response.
The fence is scoped default-permit in both layers, as the output fence is and
for the same reason: nothing judged the ask before, and a default-deny would
refuse every module that reads an EnvironmentConfig on upgrade. Every layer
that scopes the action must permit each selector. A refusal is a fatal result
that states the module, the kind, the name or labels, the namespace where set,
the requirements entry and the layer. The runtime doesn’t relay the refused
ask, so Crossplane doesn’t fetch. Unlike the output fence, the read fence judges
a response with a fatal result too, because the ask travels whatever the
results say. A selector
with no apiVersion or kind can’t be judged by any rule and is refused with
its own sentence where a layer scopes the action.
The runtime judges the requirements before it diffs the desired state, so a
response with a refused selector and a refused kind reports the selector.
requirements.schemas, the CRD schemas a module may request, isn’t fenced,
since a schema is public metadata of a kind. The request’s
required_resources isn’t edited either: it holds what Crossplane fetched for
an ask the runtime permitted on the previous call. Scoping the Function’s RBAC
remains the outer boundary, per Function; the fence narrows it per Composition
and per tenant.
Worked examples
One rule per action. The refusal each produces is in Refusal sentences.
pullModule
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example");
This permits an XR-chosen module at ghcr.io/example/greeter and refuses
ghcr.io/example-evil/greeter: the hierarchy follows path boundaries. A principal.namespace condition narrows it per tenant.
spendCredential
In a compositionPolicy, for the pull credential of an XR-chosen module:
permit (principal, action == Action::"spendCredential",
resource == Credential::"regcred")
when { context has repository &&
context.repository in Repository::"ghcr.io/example" };
This permits regcred for a module chosen from ghcr.io/example/greeter. It
refuses ghcr.io/other/greeter, and it refuses an env binding or a
requires.credentials entry that names regcred, because neither has a
repository. Permit those with a second rule that doesn’t test
context.repository.
In the operator policy, which never sees a repository:
permit (principal, action == Action::"spendCredential",
resource == Credential::"cmdb");
A module whose manifest lists credentials: [cmdb, db] is refused for db.
setEnv
permit (principal, action == Action::"setEnv", resource)
when { principal.namespace == "team-a" &&
context.keys.contains("DATABASE_URL") };
This permits the env bindings as a set for team-a when DATABASE_URL is among
the bound names. Each binding’s credential still needs a spendCredential
permit in the same layer.
usePrivateTmp and grantEgress
The minimal policy shows both. In a compositionPolicy, a
usePrivateTmp rule scopes the action and narrows it for every request of the
step. A grantEgress permit for example.com covers
api.example.com, example.com and *.example.com with GET, and refuses a
rule that lists methods: [GET, POST] on its POST. context.path is the
rule’s pathPrefix, so context.path like "/v1/*" narrows by path.
requireSignature
permit (principal, action == Action::"requireSignature", resource)
when { resource in Repository::"ghcr.io/secure" };
Modules pulled from under ghcr.io/secure need a cosign signature that a
--cosign-key key verifies, or a keyless one by a trusted signer. Modules from
ghcr.io/open/greeter run unsigned. A required HTTP source is refused before
any fetch, since OCI artifacts alone can be signed. A Path source is never
required.
trustSigner
permit (principal, action == Action::"requireSignature", resource)
when { resource in Repository::"ghcr.io/acme/modules" };
permit (principal, action == Action::"trustSigner", resource)
when {
resource in Repository::"ghcr.io/acme/modules" &&
context.issuer == "https://token.actions.githubusercontent.com" &&
context.identity like "https://github.com/acme/modules/.github/workflows/release.yml@refs/tags/v*"
};
A keyless signature on a module under that repository counts on one condition: its
Fulcio certificate was issued to the acme/modules release workflow on a version
tag, authenticated by GitHub Actions. like takes * as a wildcard. The runtime
verifies the signature against the trusted root first. The rule sets which
verified signers are trusted and does nothing else, so a rule with no when trusts
every identity the root’s authorities certified.
dialAddress
forbid (principal, action == Action::"dialAddress", resource)
when { context.ip.isInRange(ip("203.0.113.0/24")) || context.ip.isLoopback() };
permit (principal, action == Action::"dialAddress", resource)
when { context.ip.isInRange(ip("10.96.0.0/12")) };
The runtime judges a dialed address against an operator forbid first, then the
permit holes, then the default block list. Here the forbid blocks a public
range and loopback, and the permit opens an in-cluster range the default list
refuses. A permit inside a range a forbid covers never takes effect. A || is the union of its tests, a bare address literal is a
/32 or /128, and a rule with no when applies to every address. The block
list and budgets are on the HTTP egress page.
composeResource
To confine a step to adding PodDisruptionBudgets:
permit (principal, action == Action::"composeResource", resource in Group::"policy")
when { context.change == "add" };
To keep every module from composing RBAC or Secrets, an operator needs a
permit beside the forbid:
forbid (principal, action == Action::"composeResource", resource)
when { resource in Group::"rbac.authorization.k8s.io" || resource == Kind::"core/Secret" };
permit (principal, action == Action::"composeResource", resource);
function validate can’t judge output offline. It marks a step whose
compositionPolicy scopes the action with composeResource on its OK line, and
with --resolve it warns where a kind the module’s manifest declares it composes
would be refused.
requireResource
To let a step read the EnvironmentConfig its composite resource specifies:
permit (principal, action == Action::"requireResource",
resource == Kind::"apiextensions.crossplane.io/EnvironmentConfig")
when { context has name };
An operator who keeps every module’s reads inside the tenant’s namespace, Secrets off limits and the cluster-scoped Crossplane kinds open:
forbid (principal, action == Action::"requireResource", resource)
when { resource == Kind::"core/Secret" };
permit (principal, action == Action::"requireResource", resource)
when { context has namespace && context.namespace == principal.namespace };
permit (principal, action == Action::"requireResource",
resource in Group::"apiextensions.crossplane.io");
A selector that omits the namespace and selects a namespaced kind matches no
permit, so a module can’t read across namespaces by leaving the field out.
Guard a value test with has. Cedar treats a rule that reads an absent
attribute as unmatched, and an unmatched forbid is no fence.
function validate can’t judge an ask offline. It marks a step whose
compositionPolicy scopes the action with requireResource on its OK line, and
with --resolve it warns where a kind the module’s manifest declares it
requires would be refused.
Refusal sentences
A refused capability is a fatal result that states the module (module oci ghcr.io/example/greeter@sha256:… requires …) and the layer that refused it.
function validate prints the same sentences under the step. This table gives
the sentence for each requires entry, by who refuses it:
requires entry | no --sandbox-policy-file | the composition layer refuses | the operator layer refuses |
|---|---|---|---|
requires.filesystem.privateTmp | requires a private /tmp (requires.filesystem.privateTmp), but the runtime has no --sandbox-policy-file, which is required to grant sandbox capabilities | requires a private /tmp (requires.filesystem.privateTmp), which the compositionPolicy does not permit for this request | requires a private /tmp (requires.filesystem.privateTmp), which the operator policy (--sandbox-policy-file) does not permit for this request |
requires.egress.http[i], per method | requires egress (requires.egress.http), but the runtime has no --sandbox-policy-file, which is required to grant egress (grantEgress) | requires egress GET to host "api.example.com" (requires.egress.http[0]), which the compositionPolicy does not permit | requires egress GET to host "api.example.com" (requires.egress.http[0]), which the operator policy (--sandbox-policy-file) does not permit |
requires.env (setEnv) | requires env [API_TOKEN] (requires.env), but the runtime has no --sandbox-policy-file, which is required to grant sandbox capabilities | requires env [API_TOKEN] (requires.env), which the compositionPolicy does not permit (setEnv) | requires env [API_TOKEN] (requires.env), which the operator policy (--sandbox-policy-file) does not permit (setEnv) |
an env binding’s credential (spendCredential) | as in the preceding row | requires env API_TOKEN from credential "apikeys", which the compositionPolicy does not permit (spendCredential) | requires env API_TOKEN from credential "apikeys", which the operator policy (--sandbox-policy-file) does not permit (spendCredential) |
requires.credentials[i] | requires credential "cmdb" (requires.credentials[0]), but the runtime has no --sandbox-policy-file, which is required to grant step credentials (spendCredential) | requires credential "cmdb" (requires.credentials[0]), which the compositionPolicy does not permit | requires credential "cmdb" (requires.credentials[0]), which the operator policy (--sandbox-policy-file) does not permit |
a change to the desired state (composeResource, after the run) | not refused: no policy file narrows the output | composed apps/Deployment "deployment" (modify), which the compositionPolicy does not permit (composeResource); for the composite resource composed platform.example.org/WebApp (composite, modify), which … | composed core/Secret "db-password" (add), which the operator policy (--sandbox-policy-file) does not permit (composeResource) |
a resource selector in the response’s requirements (requireResource, after the run) | not refused: no policy file narrows the reads | required core/Secret "db-password" in namespace "team-b" (requirements.resources["db"]), which the compositionPolicy does not permit (requireResource); for a match by labels required core/Secret with labels team=a,tier=gold (requirements.resources["secrets"]), which … | required core/Secret "db-password" in namespace "team-b" (requirements.resources["db"]), which the operator policy (--sandbox-policy-file) does not permit (requireResource) |
Signature refusals
When a rule requires a signature, a module is refused with one of these:
- no key or trusted root to verify with:
cannot verify module oci ghcr.io/secure/greeter@sha256:…: the operator policy requires a cosign signature, but the runtime has neither --cosign-key nor --cosign-trusted-root to verify it - an HTTP source:
module.http "https://example.com/fn.wasm" requires a cosign signature (operator policy), but only OCI modules can be signature-verified - an HTTP source whose URL the rules can’t be matched against, when the
policy has a
requireSignaturerule:module.http.url "…" must have a normalized path (no . or .. segments, no empty segments): the operator policy requires cosign signatures by location (requireSignature), and this one cannot be read, or the same aftermust name a host and carry no user information - a verified keyless signer no rule trusts:
cannot verify module oci …: no valid cosign signature for <ref>: keyless signature by <identity> (issuer <issuer>) is not trusted for <repository>: no trustSigner rule in the operator policy permits it
The module.from fences
These refuse before the module is resolved, prefixed cannot resolve module::
- no
compositionPolicyat all:module.from: status.module of the composite resource names a OCI source, but the Input has no compositionPolicy: a module the composite resource chooses must be permitted by the compositionPolicy's pullModule rules, or its author could point the runtime at any host - no matching
pullModulepermit:module.from: status.other of the composite resource names ref "index.docker.io/someone/else", which the compositionPolicy does not permit (pullModule)(ornames manifestURL "…"for an HTTP source’s manifest) - a pull credential no
spendCredentialpermit covers:module.from: status.module of the composite resource names credentials "registry", which the compositionPolicy does not permit (spendCredential) for "ghcr.io/example/greeter": a module chosen by the composite resource cannot spend a step credential (the registry host would be its author's) unless the compositionPolicy permits it for that repository; otherwise pull it with the runtime's Docker config or anonymously
A compositionPolicy that doesn’t parse is compositionPolicy is invalid: cannot compile the compositionPolicy as Cedar: <Cedar's error>.
Load-time errors
The runtime compiles the operator policy when it starts, and function validate
does when it runs. A document that can’t be compiled stops both. The runtime
prints the error and exits 1. function validate prefixes it with function validate: and exits 2.
cannot read operator policy: open <path>: <error>cannot compile the operator policy <path>: <Cedar's parse error>operator policy: dialAddress rule "<id>": <reason>, where<id>is the rule’s id as Cedar numbers the file (policy0for the first rule) and the reason is one of:must scope the action as == Action::"dialAddress", not an "in" setmust not constrain the principal or resource: the dial has neither identitytakes at most one when conditionmay only use a when condition, not unlessthe condition must be a single ip testunsupported operation "isMulticast" (an ip test uses isInRange, isLoopback or ||)an ip test may only test context.ipisInRange takes context.ip and one ip("CIDR") literal,isLoopback takes context.ip and no argument,isInRange takes one ip("CIDR") literal, or"<value>" is not an ip literal: <reason>
A policy with a usePrivateTmp rule makes the runtime create a temporary
directory under TMPDIR at startup, and exit 1 if it can’t: the operator policy grants a private /tmp (usePrivateTmp), but the runtime cannot create one under <dir>: <error>. function validate doesn’t run this check. The startup
warnings about a cosign flag without its matching policy rule are on the
signatures page.
Testing a policy
function validate applies both layers to a Composition offline, with the flags
the runtime is started with:
function validate composition.yaml \
--sandbox-policy-file policy.cedar \
--xr xr.yaml \
--resolve
--xr gives the principal, and without it function validate uses the zero
principal. The options, output and exit codes are on the
offline validation page.
Further reading
The design record is the three-layer authorization model.
HTTP egress
This page is for operators who let modules make HTTP and HTTPS requests. It
covers what to enable, the budgets, the block list and CIDR rules, and what
the runtime refuses and logs. It assumes a runtime started with a Cedar
--sandbox-policy-file (see operator grant policy); the
guest-side client is covered in write a module.
A module never opens a socket. The runtime resolves the name and checks the address against its block list, then sends the request over TLS with its own roots. A request the runtime doesn’t perform is a transport error that states the reason, never a trap, and any status from the server is a response.
A request is allowed when all three layers agree, and in no other case:
- The operator’s Cedar policy enables egress.
- The module’s manifest lists the hosts, methods and paths it needs.
- The Composition’s
compositionPolicymay narrow that list.
Credentials and egress
With egress on, a module can send any host it’s granted whatever its request
contains, including the step credentials granted to it. A grantEgress
permit that matches any host grants every public host. Grant narrowly, prefer pathPrefix in the manifest’s rules, and pair the
capability with --cosign-key so modules your organisation signed alone run
(see signatures).
Enabling egress
With no --sandbox-policy-file, egress isn’t grantable: a module that
requires it fails with a fatal result before it runs. With one, egress is
default-deny and the policy opens it through two actions:
grantEgressdecides which hosts, methods and paths a caller’s modules (principal.namespace,principal.xrKind) may reach.dialAddressdecides which resolved IP addresses the runtime may dial, overcontext.ip.
function --sandbox-policy-file /etc/guestfn/policy.cedar \
--egress-rate-limit-per-minute 60 --egress-rate-limit-burst 10
// Only team-a may grant egress, and only to *.googleapis.com over GET/HEAD.
permit (principal, action == Action::"grantEgress", resource)
when { principal.namespace == "team-a" &&
resource in HostPattern::"googleapis.com" &&
["GET", "HEAD"].contains(context.method) };
// Open one in-cluster service range: the default block list already
// refuses 10.0.0.0/8, and a permit punches a hole in it.
permit (principal, action == Action::"dialAddress", resource)
when { context.ip.isInRange(ip("10.96.0.0/12")) };
// Block a public range the default list does not cover. A forbid wins
// over any permit for the same address, so never pair it with a hole
// inside it.
forbid (principal, action == Action::"dialAddress", resource)
when { context.ip.isInRange(ip("203.0.113.0/24")) };
The schema and the refusal sentences are in the Cedar policy reference.
Budgets
Each run has fixed budgets: timeout 10 seconds, maxRequests 16,
maxResponseBytes 4 MiB and maxRedirects 5. The rate limit alone is
tunable, through --egress-rate-limit-per-minute and
--egress-rate-limit-burst.
A request’s body is at most 4 MiB as well. The host reads the body before
it asks the policy, and refuses a longer one with sandbox.egress: the request body exceeds 4194304 bytes (maxRequestBytes).
The run’s remaining deadline also bounds each request. The deadline is
limits.timeout or --module-timeout, and the time a guest waits for the
host’s HTTP answer is credited back to that budget, once for requests that
overlap. The time the guest takes to send a body isn’t. A request is cut
short at the remaining deadline when that comes before the 10 seconds, and the
run then ends as a timeout, so the guest can’t handle that error.
Block list and CIDR rules
The default block list refuses these ranges:
- loopback
- link-local, which includes the metadata endpoint of a cloud provider
- RFC 1918
- carrier-grade NAT (
100.64.0.0/10) - IPv6 unique-local
- the prefixes that embed an IPv4 address in an IPv6 one, which are the
IPv4-compatible prefix, NAT64 (
64:ff9b::/96and64:ff9b:1::/48), 6to4 (2002::/16) and Teredo (2001::/32) - the unspecified, multicast, benchmarking (
198.18.0.0/15) and reserved ranges,192.0.0.0/24among them
It applies to every address a name resolves to. A zoned IPv6 literal such as
[::1%25lo] is never dialled. The runtime dials the address it checked, so a
name can’t rebind between the check and the connection.
A dialAddress forbid adds a range to the list and a permit punches a
hole in it, and a forbid wins over a permit. To reach a loopback service
in a local test, both 127.0.0.0/8 and ::1/128 need a permit.
Each dialAddress condition is one IP test: context.ip.isInRange(ip("CIDR")),
context.ip.isLoopback(), or a || of those. The conditions compile at load
into an ordered prefix list, and Cedar isn’t evaluated per resolved IP. A
malformed rule is refused at startup, and function validate reports it too.
HTTP_PROXY isn’t honoured, because the host must see the destination
address to judge it.
Manifest rules
The manifest’s requires.egress.http rules (see
module manifests) are what the module requests. Each
rule has one of host (an exact name) and hostPattern
(*.example.com: every name under it, not the apex), at least one of
GET HEAD POST PUT PATCH DELETE OPTIONS, and an optional pathPrefix the
normalized path must start with.
# guestfn.yaml
requires:
egress:
http:
- host: api.example.com
methods: [GET]
pathPrefix: /v1/prices/
- hostPattern: "*.googleapis.com"
methods: [GET, POST]
The runtime checks every request and every redirect hop against these rules.
The Input’s compositionPolicy narrows them when it scopes
grantEgress, and a rule is then refused unless one of its permits matches it.
When an XR author picks a module through module.from, the module’s manifest
comes with it, and both Cedar layers still gate every rule it declares.
A rule the operator’s policy doesn’t permit is a fatal result before the module runs:
module oci … requires egress GET to host "evil.example.com" (requires.egress.http[0]), which the operator policy (--sandbox-policy-file) does not permit
A runtime with no --sandbox-policy-file refuses any egress a manifest
requires:
… requires egress (requires.egress.http), but the runtime has no --sandbox-policy-file, which is required to grant egress (grantEgress)
Audit log and metric
The runtime writes one log line per request, with the module reference and digest. The line contains:
- method, host and path, never the query, headers or body
- the status, or the reason for the refusal
- response bytes, duration and outcome
- for a blocked address, the resolved address and the block-list entry, which the guest isn’t told
A redirect adds one line per hop. Repeated calls without a grant or past
maxRequests log one info line, then debug lines.
Each request also increments guestfn_module_http_requests_total{outcome},
where the outcome is ok, refused, budget or error. The series has no
host label.
Readiness and warm-up
This page is for operators who wire Kubernetes probes for a function-wasm pod
and decide whether to preload modules. It assumes Crossplane runs the function
from a package with a DeploymentRuntimeConfig.
Probes
The runtime reports readiness in two places: the gRPC health service
(grpc.health.v1.Health) on the function port, and plain HTTP /readyz on
--health-address (:8081), which also serves /livez. Readiness means the
caches are open, the engine is up and the modules named by --warm-modules
(none by default) are loaded. Until then the runtime answers RunFunction with
UNAVAILABLE, and Crossplane retries the step.
Use the HTTP endpoints for Kubernetes probes. Crossplane runs functions with
mTLS on the function port and kubelet’s gRPC probe dials without credentials, so
a grpc: probe never succeeds outside --insecure. The health port is
plain HTTP with no authentication; the side ports
shows a NetworkPolicy for it.
apiVersion: pkg.crossplane.io/v1beta1
kind: DeploymentRuntimeConfig
metadata:
name: function-wasm
spec:
deploymentTemplate:
spec:
template:
spec:
containers:
- name: package-runtime
readinessProbe:
httpGet:
path: /readyz
port: 8081
livenessProbe:
httpGet:
path: /livez
port: 8081
Warm-up
A ready pod hasn’t necessarily loaded any module. The first request for a
module on a pod compiles it. The compiled code is signed per process, and a
restart compiles again even on a volume, which keeps the fetched module and nothing more.
--warm-modules moves that work ahead of readiness.
With the flag set, the runtime listens at once but reports NOT_SERVING (and /readyz answers 503)
while it loads the listed modules, one after another. A RunFunction call in
that time gets UNAVAILABLE (the function is not ready) and runs nothing. With a warm volume each load takes
milliseconds. With a cold cache each costs one compile. The runtime reports
SERVING when every entry has loaded or failed. /livez answers throughout, so
a liveness probe is unaffected.
Warm-up runs the path a request does, so a warmed module is a memory hit for
its first request. With --enable-memory-cache=false the artifact stays on
disk instead.
Failed entries
A failed entry is logged as Cannot warm module with the entry and the reason,
and never holds readiness back. The module loads on its first request, and the
pod remains ready. Troubleshooting covers a readiness
probe that fails for a while after start.
Trusted root
With --cosign-trust-instance, the first fetch of the Sigstore trusted root
runs right before the modules and is bounded to one minute. It never holds
readiness back either; signatures covers what a pod does
without a root.
Metrics
This page is for operators building dashboards and alerts on the runtime. It
lists every series served on --metrics-address and the formats it speaks.
The endpoint is :8080/metrics by default, and an empty value disables it.
It’s plain HTTP with no authentication: admit it from the scraper’s namespace
alone (the side ports). Probes are on
Readiness and warm-up.
| metric | labels | meaning |
|---|---|---|
guestfn_module_requests_total | outcome = ok, refused, error, skipped | requests by outcome |
guestfn_module_run_duration_seconds | outcome = ok, error, timeout | histogram of one guest run, instantiate to response; a wait for a run slot isn’t part of it, and a request cut short while waiting for one isn’t counted. For function-oci a run is the VM’s boot or restore to the response: the runtime stops the VM after it has returned the response, and that time isn’t part of the histogram |
guestfn_module_runs_in_flight | gauge of guest runs executing now, at most --max-concurrent-runs. function-oci counts a run until its VM is stopped, some milliseconds after the response, since the run keeps its slot until then. A gauge held at the bound means requests are queuing for a slot | |
guestfn_module_hostcall_duration_seconds | histogram of the time a run spent inside host imports (the log import, HTTP egress over wasi:http, and WASI); the rest of run_duration_seconds is guest compute | |
guestfn_module_compile_duration_seconds | histogram of Wasmtime compile time on compiled-cache misses | |
guestfn_module_fetch_duration_seconds | source = oci, http, path | histogram of fetch and verify time, blob-cache hits and served-file reads included |
guestfn_module_cache_events_total | cache = compiled (memory), compiled-disk, blob, snapshot; event = hit, miss, stale, timeout | cache lookups; timeout is a cold load cut short by --module-compile-timeout; stale is an artifact on disk that Wasmtime refused, and appears for compiled-disk and snapshot. snapshot is function-oci’s VM snapshots under --enable-vm-snapshots: a hit is a run restored from one and a miss is a snapshot made. A stale there is a snapshot the sweep removed or the store refused |
guestfn_module_snapshot_duration_seconds | histogram of the time function-oci takes to make a VM snapshot of an image: the boot, the pause and the two files | |
guestfn_module_cache_bytes | cache = compiled-disk, blob | bytes on disk per store, measured every ten minutes. A sparse file counts by what the disk allocated for it, and function-oci’s VM snapshots count under compiled-disk |
guestfn_module_http_requests_total | outcome = ok, refused, budget, error | HTTP requests modules made through the host (requires.egress.http) |
guestfn_module_memory_denials_total | reason = limit, pool | guest memory and table growths denied; the guest sees memory.grow or table.grow fail |
guestfn_trusted_root_refreshes_total | outcome = updated, unchanged, error | refreshes of the Sigstore trusted root |
guestfn_trusted_root_last_refresh_timestamp_seconds | Unix time of the last successful refresh of the trusted root, 0 until the first; time() minus this value is the root’s age |
The requests_total outcomes:
ok: the module ran and returned a response.refused: the runtime declined the request before the run (input, policy, grants, limits, resolution or verification), or refused the module’s response at therequireResourceorcomposeResourcefence. In the second case the module ran, so the run is inrun_duration_secondstoo.error: the load or the run failed.skipped: the composite resource chose no module andmodule.allowEmptyallowed it, so nothing ran (logged asNo module chosen by the composite resource).
The http_requests_total outcomes:
ok: the server answered.refused: the grant or the egress policy refused the request (HTTP egress).budget: a per-run budget or the timeout was hit.error: the request failed.
The memory_denials_total reasons:
limit: the growth passed the run’s ceiling (limits.memoryor--module-memory-limit).pool:--max-total-run-memorycouldn’t serve the growth before the run’s deadline.
The trusted-root series exist when --cosign-trust-instance is set (signatures) and not otherwise, and every outcome starts at zero. The refreshes_total outcomes:
updated: a root was put in use, the first one or one that differs from the last. The memo of verified modules is forgotten with it.unchanged: the same root was fetched again.error: the fetch failed and the last good root stays. The log has the reason.
Alert on the root’s age growing past twice the refresh interval (--cosign-tuf-refresh), and on the error outcome moving.
No metric has a module or host label, because the sets of digests and hosts a Function serves are unbounded. The logs include the module reference and digest, and the egress audit line states the host.
Formats
The main format is OpenMetrics
1.0 (application/openmetrics-text; version=1.0.0). A scraper whose Accept
header asks for the classic Prometheus text format without accepting
OpenMetrics gets text/plain; version=0.0.4. Both contain the same series.
gRPC server metrics
The runtime serves the gRPC server series of the Prometheus gRPC interceptor, with the names and labels function-sdk-go uses:
grpc_server_started_totalgrpc_server_handled_total, with agrpc_codelabel holding the gRPC code namegrpc_server_msg_received_totalgrpc_server_msg_sent_total
Each is labelled grpc_type, grpc_service and grpc_method.
Unary calls (RunFunction, health Check) alone are counted. Streaming methods (reflection, health Watch) exist from startup, at zero until the first call.
For latency, use guestfn_module_run_duration_seconds.
Trust model
This page is for operators deciding what a function-wasm installation trusts. It names who can do what, and which policy or flag limits each party. It assumes Composition authors are trusted and that composite resource (XR) authors and module code aren’t. The reasoning and the threats considered are in the design record for the trust model.
Module privileges
A module is the code of the Composition author. It gets nothing beyond what the
Composition’s step and the operator’s policy grant it. It sees the request’s
observed state, desired state and context. Of the step credentials, it sees the granted ones alone: those its
manifest names in a requires.env
binding or in requires.credentials, and that both Cedar layers permit
through spendCredential. The runtime removes every other credential from
the request before the module runs.
The credential that pulled the module (module.oci.credentials) belongs to
the host. The runtime never forwards it, whatever the manifest asks.
The sandbox protects the runtime, and every other Composition sharing the Function, from a module that crashes, loops or exhausts memory. Beyond that, a module gets nothing that its manifest omits or a policy layer refuses (Cedar policy):
- A private
/tmpthat exists for one request. Host directories can’t be mounted. - The environment variables its manifest binds to step credentials.
Non-secret configuration goes in
config. - HTTP requests through the host (HTTP egress).
What a module writes to the desired state can be fenced per kind with
composeResource (the output fence),
and what it asks Crossplane for through the response’s requirements with
requireResource (the read fence). Both
narrow the Function’s RBAC per Composition and per tenant. The RBAC remains
the outer boundary, so scope it to what the modules should see.
Modules chosen by an XR author
With module.from, the XR author picks the module. Use it where you
trust XR authors to choose code, and nowhere else. Limit the choice in two ways:
- Permit sources with
pullModulerules in the Input’scompositionPolicy.OCIandHTTPsources need one. Without it, the XR author could point the runtime at any host. - Require signatures with
--cosign-keyor the keyless options in Signatures.
The runtime reads compositionPolicy and limits from the Input alone,
never from the XR. An XR author can choose code but can’t widen its
permissions, grants or budget. The runtime enforces every rule on every request, because Crossplane never
installs the Input’s CRD. function validate runs
the same checks over a Composition offline.
Credentials and the registry pull
A source read from the XR can specify a step credential where a
spendCredential permit matches it and a pullModule permit admits the
repository, and nowhere else. Otherwise the XR author would choose the registry host that
receives the secret. The runtime sends the pull credential to a registry
as HTTP Basic when the registry challenges for it, or exchanges it for a bearer
token.
Without such a permit, the runtime pulls an XR-chosen module anonymously or
with its own Docker config. Mount a Docker config through a
DeploymentRuntimeConfig and set DOCKER_CONFIG. Its credentials apply
to their registry host alone.
The credential protects the pull, never the cache. The runtime caches a
module’s bytes by content digest and serves them, without a fetch, to any
Composition on the runtime that states the digest, from an OCI, HTTP or
Path source alike. A private module remains private as long as no
Composition another tenant can read quotes its digest. The runtime checks
the credential at the first load of a digest in a process, for the module’s
bytes and its manifest alike, and the signature once per repository and
digest. A warm request doesn’t contact the registry. A credential withdrawn later stops a cached module at
its next cold load: a restart, an idle eviction past the ten-minute TTL with the
disk entry swept, or a key rotation under requireSignature. To stop a
module now, forbid it: the pullModule fence for a module.from source, or
requireSignature on its repository with the signature revoked.
The cache directory
The caches under /tmp/guestfn-cache belong to the runtime. The
runtime checks each tier before it serves it. Fetched modules and manifests are
verified against their digest on every read. Compiled artifacts, native
code that Wasmtime loads without a check of its own, carry an HMAC under a
key the process draws at startup and never writes anywhere, so an artifact
this process didn’t write, planted or left by an earlier process, is refused
and the module is compiled again
(the design record for the cache key). Back the
directory with an emptyDir, or with a volume for this pod alone to keep the
fetched modules across restarts
(cache storage).
Egress
A module granted egress can forward its whole request to the hosts its rules allow, step credentials included. The policy layers alone grant egress: a manifest can request it, and an XR author can’t widen it. Every request leaves an audit line with the module digest.
Require signatures wherever egress is granted, so that sending data out is the privilege of code you’ve approved (Signatures).
Pinning
A remote module that a Composition names is pinned by a digest the
Composition states: the OCI reference’s manifest digest or http.digest.
The runtime verifies the manifest and layer digests when it fetches, so the
code can’t change without the Composition changing. This doesn’t hold for
modules chosen with module.from, which the XR author picks, or for Path
sources, which have no digest.
Signatures
This page is for operators who want the runtime to refuse modules that aren’t signed by a signer they trust. It covers key-based and keyless verification, the Sigstore trusted root and per-repository requirements. It assumes cosign 3 and OCI modules; how to sign in CI is out of scope beyond the cosign commands shown.
Without a --sandbox-policy-file, a verifier makes every module need a
signature: --cosign-key, --cosign-trusted-root or
--cosign-trust-instance. With a policy file, its requireSignature rules
select the repositories that must be signed and the rest run unsigned.
--cosign-key then supplies keys and does nothing else (see per repository).
OCI artifacts alone have a cosign signature, so a source of another type is
refused wherever a signature is required. With --cosign-key alone, that’s
every Path and HTTP source. Under a policy it’s an HTTP source whose URL a
requireSignature rule matches. An HTTP URL the rules can’t be matched
against, one with user information or with ., .. or empty path segments,
is refused wherever the policy has a requireSignature rule. A Path source
has no repository, so no rule matches it and it runs unsigned.
Key-based signatures
Sign a module with cosign sign --key cosign.key <ref> and start the runtime
with --cosign-key cosign.pub. A DeploymentRuntimeConfig mounts the key and
sets the flag or COSIGN_KEY.
The runtime verifies a module once per repository and manifest digest per
process, before it consults any cache. A verdict holds for one repository:
the runtime verifies the same digest in another repository there, against
that repository’s referrers and its trustSigner rules. An artifact
left on a persisted volume by a runtime without the key isn’t served by one
with it.
cosign 3 stores a signature as a Sigstore bundle: a DSSE envelope around an
in-toto statement whose subject is the module’s manifest digest, pushed as an
OCI 1.1 referrer of that manifest. The runtime lists the referrers through
the registry’s referrers API. Where the registry has none (GHCR,
registry:3), it reads the sha256-<hex> tag index cosign maintains, with
the same credentials as the pull.
A module is signed when one bundle verifies with a configured key and its
statement is a cosign signature of that digest (predicate type
https://sigstore.dev/cosign/sign/v1). Other attestations among the
referrers, such as SLSA provenance, never admit a module. For a key-based
bundle the keys are the trust root, so its key hint and transparency-log
entries aren’t consulted.
cosign 2’s legacy signatures (the sha256-<hex>.sig tag, which cosign 3
writes with --new-bundle-format=false) aren’t read. A module signed in
that way alone counts as unsigned and is refused: re-sign it with cosign 3.
Keyless signatures
A keyless signature is made with cosign sign <ref> under an OIDC identity.
This repository’s release workflow signs the examples it publishes that way.
The bundle has a Fulcio certificate valid for ten minutes, a Rekor
transparency-log entry and an RFC 3161 timestamp instead of a key hint.
The trusted root
The runtime verifies a keyless bundle against a Sigstore trusted root, which
lists the Fulcio authorities, the Rekor and certificate-transparency keys and
the timestamp authorities, each with a validity window. Pass it as
--cosign-trusted-root trusted_root.json (COSIGN_TRUSTED_ROOT).
cosign initialize fetches the root of the public-good instance over TUF:
cosign initialize
cp ~/.sigstore/root/tuf-repo-cdn.sigstore.dev/targets/trusted_root.json .
Verification is offline and rests on the signing time, not the clock. Every RFC 3161 timestamp in the bundle must verify with a timestamp authority of the root, and the Rekor entry’s signed entry timestamp with a Rekor key. The certificate must chain to a Fulcio authority and be valid at each of those times. The runtime then checks the entry’s inclusion proof and signed checkpoint, and last the signature. A bundle with no verifiable signing time is refused, and so is a bundle whose certificate had expired at signing time.
Trusting a signer
A trusted root alone admits nothing. The signer the certificate names (its
OIDC issuer and its subject alternative name, a workflow URI or an email)
must be trusted for the module’s repository by a trustSigner rule in the
operator policy, default-deny. The repository also needs its
requireSignature rule (see per repository):
permit (principal, action == Action::"requireSignature", resource)
when { resource in Repository::"ghcr.io/jonasz-lasut/guestfn/examples" };
permit (principal, action == Action::"trustSigner", resource)
when {
resource in Repository::"ghcr.io/jonasz-lasut/guestfn/examples" &&
context.issuer == "https://token.actions.githubusercontent.com" &&
context.identity == "https://github.com/jonasz-lasut/guestfn/.github/workflows/publish-examples.yml@refs/heads/main"
};
With that policy and the trusted root, the examples this repository publishes
run on the identity of its publish workflow, with no countersignature:
publish-examples.yml, run by hand from main. A certificate records the
repository’s name and the workflow at signing time. A rule for an artifact
signed before a rename has to state the identity of that time.
A keyless signature by any other signer is refused:
keyless signature by <identity> (issuer <issuer>) is not trusted for <repository>: no trustSigner rule in the operator policy permits it
A keyless bundle met by a runtime with neither flag is refused:
keyless signature cannot be verified: the runtime has neither --cosign-trusted-root nor --cosign-trust-instance
--cosign-key and a trusted root combine. The runtime checks a bundle with a
key hint against the keys and one with a certificate against the root, and a
module is signed when one of its bundles verifies.
Fetching the trusted root over TUF
The trusted root lists the validity window of each key and authority, and a
bundle verifies against the material valid at its signing time. A file that
predates a rotation can’t verify bundles signed with the new material, so the
root has to be refreshed. --cosign-trusted-root is the air-gapped mode. The
runtime reads the file and nothing else, so you refresh it yourself, such as
through a mounted ConfigMap that cosign initialize rewrites.
--cosign-trust-instance public-good (COSIGN_TRUST_INSTANCE; also
staging and github) fetches the root instead and refreshes it while
serving. You can’t set both flags. The refresh interval,
--cosign-tuf-refresh, is described in runtime flags.
The runtime verifies the metadata chain starting from the TUF root built into
the runtime. It caches the verified
metadata and the root under /tmp/guestfn-cache/tuf/<instance>, outside
the --max-cache-size sweep. A volume under the cache root preserves it
across restarts.
At startup the runtime fetches the root before it warms modules and reports ready, giving up after one minute. It then falls back to the cache, re-verified offline from the built-in root, until the cached metadata expires. With neither available, the runtime still starts and refuses every keyless signature until a refresh succeeds, retried once a minute:
keyless signature cannot be verified: the trusted root of public-good has not been fetched yet (the last attempt failed: …)
Key-signed and unsigned modules, readiness and liveness are unaffected.
While serving, a changed root replaces the one in use and clears the
memo of verified modules, so a module whose signer the new root no longer vouches
for is verified again on its next request. A failed refresh keeps the last
good root. Verification never touches the network: a failed refresh makes the
root older and never slows a request. The metrics
guestfn_trusted_root_refreshes_total{outcome} and
guestfn_trusted_root_last_refresh_timestamp_seconds show the refreshes
and the root’s age (see metrics).
function validate --resolve --cosign-trust-instance public-good … runs the
same fetch, or reads the same cache, before it verifies, so you can rehearse
the flags offline. Without --resolve nothing is fetched. A private TUF
mirror isn’t supported.
Requiring signatures per repository
An operator policy (--sandbox-policy-file) can require a signature per
repository through a requireSignature rule over the same Repository
hierarchy the module fence uses. The repositories you name must be
signed, and no others:
permit (principal, action == Action::"requireSignature", resource)
when { resource in Repository::"ghcr.io/acme/prod" };
A repository without a rule needn’t be signed. A signature no configured key can check is refused: the rule fails closed. A required module that’s unsigned, or that the runtime has no flag to verify, is refused before any cache is consulted.
Startup warnings
The runtime warns at startup when a signing flag and the operator policy don’t match, and serves anyway. Each line says what it leaves unverified:
--cosign-key is set but the operator policy has no requireSignature rule: no module will be signature-verified
--cosign-trusted-root is set but the operator policy has no trustSigner rule: no keyless signature will be trusted
the operator policy has trustSigner rules but neither --cosign-trusted-root nor --cosign-trust-instance is set: every keyless signature will be refused
The second line names --cosign-trust-instance when that flag is set
instead. function validate --resolve adds a warning of its own for a module
that requires egress when it can’t verify signatures (see the
warnings of function validate).
Verifying a function package
This page is for operators who want proof of where a function package came from before a cluster runs it. It covers the packages themselves, function-wasm and function-oci. The signatures of the modules a function runs are a separate matter, on the Signatures page.
The signature
A workflow in this repository signs every release of both packages with cosign, keyless, in both registries: ghcr.io/jonasz-lasut/<function> and its mirror xpkg.upbound.io/jonasz-lasut/<function>. The signature binds the package’s digest to that signing workflow. A package that verifies is one this repository’s release process signed.
Verify a package with the signer’s identity and its issuer:
cosign verify ghcr.io/jonasz-lasut/function-wasm:v1.1.0 \
--certificate-identity https://github.com/jonasz-lasut/guestfn/.github/workflows/supplychain.yml@refs/heads/main \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
The identity is the same for every release of both functions since function-wasm v1.0.0 and function-oci v0.1.0, so one rule covers them all. function-wasm v0.6.0 and earlier date from before the repository took its present name, and their identity has jonasz-lasut/function-wasm where this one has jonasz-lasut/guestfn. cosign prints the digest it verified. Put that digest in the Function’s spec.package (ghcr.io/jonasz-lasut/function-wasm@sha256:...) when the cluster must run that package and no other.
In the cluster
Crossplane can make the same check before it installs a package. An ImageConfig names the packages and the signer they must have:
apiVersion: pkg.crossplane.io/v1beta1
kind: ImageConfig
metadata:
name: guestfn-functions
spec:
matchImages:
- type: Prefix
prefix: ghcr.io/jonasz-lasut/function-
verification:
provider: Cosign
cosign:
authorities:
- name: guestfn-signing-workflow
keyless:
identities:
- issuer: https://token.actions.githubusercontent.com
subject: https://github.com/jonasz-lasut/guestfn/.github/workflows/supplychain.yml@refs/heads/main
Crossplane’s own documentation describes ImageConfig and the versions that support signature verification.
Provenance
Each package also has an SBOM attestation and a SLSA provenance attestation, which gh attestation verify reads:
gh attestation verify oci://ghcr.io/jonasz-lasut/function-wasm:v1.1.0 --repo jonasz-lasut/guestfn
From function-wasm v1.0.2 and function-oci v0.3.0 the provenance records the run that built the package: the publish-function.yml workflow at the release’s tag, refs/tags/function-wasm-vX.Y.Z or refs/tags/function-oci-vX.Y.Z, with that tag’s commit. The certificate’s identity is the signing workflow on main all the same, as for the signature.
Through function-wasm v1.0.1 and function-oci v0.2.0 the provenance records the signing run on main instead, with the signing workflow and the commit main had when that run started. That commit isn’t the one the package’s code comes from. For those releases the source is the git tag, function-wasm-vX.Y.Z or function-oci-vX.Y.Z.
Troubleshooting
This page is for the operator of a function-wasm pod and for the module author whose module the runtime refuses. Find the message in the pod’s logs, in a step’s fatal result or in the output of function validate or guestfn, then follow the entry. Entries are grouped by what failed and match the current release. Each quoted message is a prefix or a fragment: match on the part that doesn’t vary.
Module load
cannot instantiate module: trap: …: the guest trapped while the runtime instantiated it, such as by panicking in its start-up code. The stack is in the stderr of the function pod.component does not implement the guestfn:function@1.0.0 world: …: the component doesn’t typecheck againstwit/guestfn-function.wit: it has norunexport (no exportrunfound) or imports something the runtime doesn’t provide. Rebuild against the currentwit/, and useguestfn inspect fn.wasmto list what the module exports and imports.cannot load module …: cannot compile module: failed to parse WebAssembly module: threads support is not enabled, or the same for another proposal: the module uses a WebAssembly proposal the engine refuses: threads, GC, function references, exceptions, tail calls, multi-memory or memory64 (ABI v2 lists what it accepts). Build the guest without that feature, which no scaffold’s toolchain emits by default.cannot load module …: cannot download module: the redirect to <url> is not followed: <host> resolves to an address the default block list refuses: the download was redirected to another host at a loopback, private or otherwise blocked address. Specify the final URL inmodule.http.url. See HTTP redirects. A manifest’s download sayscannot download manifest: …, formodule.http.manifestURL.… is not followed: not an http or https URLis a redirect to another scheme, andmore than 10 redirectsa chain longer than the runtime follows.cannot load module …: cannot fetch manifest sha256:…: manifest exceeds the size limit of 4194304 bytes: the registry answered the manifest request with more than 4 MiB, the most the OCI distribution specification asks a registry to accept. A module’s or an image’s manifest is measured in kilobytes: check what the registry stores under that digest.cannot fetch registry token: the token response exceeds the size limit of 1048576 bytesis the same bound, 1 MiB, on the answer of the registry’s token endpoint.module.http.manifestURL and module.http.manifestDigest must be set together: an HTTP source gave one of the two. The runtime reads the manifest from the URL and verifies it against the digest, so set both or neither.module.http.manifestURL "…" must be an http or https URLandmodule.http.manifestDigest "…" is not sha256:<64 hex characters>refuse a pair that’s set and malformed.module.http.url "…" must have a normalized path (…): the operator policy requires cosign signatures by location (requireSignature), and this one cannot be read, or the same aftermust name a host and carry no user information: the operator policy has arequireSignaturerule, and the rule is matched against a location that this URL doesn’t yield. Write the URL without user information and without.,..or empty path segments.cannot load module …: module is a core module, which function-wasm 1.0.0 no longer runs (ABI v1 was removed); build it as an ABI v2 component (docs/abi-v2.md): rebuild the guest as a component. For a Go guest,guestfn buildturns the core module thatgo buildemits into one; a guest written for ABI v1 is rebuilt on a current scaffold (guestfn init, then move the function over).guestfn inspectandfunction validate --resolveprint the same sentence.built fn.wasm, but the runtime would refuse it: …fromguestfn build, or a refusal fromguestfn push: the message is the runtime’s own load-time refusal. The entries before this one cover the common ones.module.oci.ref … tags are not supported: pin the reference to the manifest digest,repo@sha256:…orrepo:tag@sha256:…, asguestfn pushprints it.module.oci.ref "…": registry "…" is not a valid registry host (a host name or an IP address with an optional port, no user information): the part of the reference before the first/isn’t a host the runtime accepts as a registry. Write it ashostorhost:port, with an IP address in full (127.0.0.1, or[::1]for IPv6). Credentials belong inmodule.oci.credentials: the runtime doesn’t read auser@prefix.guestfn pushandguestfn inspectanswercannot parse reference "…"for the same reference.module.oci.ref "…": repository "…" is not a valid repository name (lowercase path components, no . or .. or empty ones): the path after the registry isn’t an OCI repository name. Use lowercase path components separated by single slashes.Repository::"…" is not the canonical name of that repository; write Repository::"…", afteroperator policy <file>:at startup orcompositionPolicy is invalid:on a request: a rule spells a registry in a way no module location has. The runtime reads a reference’s registry into its canonical form before the policies see it, soGHCR.IO/team/fnandghcr.io:443/team/fnareghcr.io/team/fn, and a rule over another spelling wouldn’t match any module. Write the name the message gives. Docker Hub isindex.docker.ioin a rule, neverdocker.io.Repository::"…" does not name a repository: registry "…" is not a valid registry host (a host name or an IP address with an optional port, no user information): the registry part of a name in a policy isn’t a host. Write it ashostorhost:port.module layer is a tar archive without /fn.wasm: aFROM scratchimage mustCOPYthe module to/fn.wasm. Preferguestfn pushororas push, which write a rawapplication/wasmlayer.
Input and admission
function validate runs the same checks as the runtime. Run it with the flags you start the runtime with: exit 1 means a step is refused and the line states the reason, and exit 2 means the tool itself failed. The fields are in the Input reference.
module.path is refused: the runtime was started without--module-dir.module.from: … names a OCI source, but the Input has no compositionPolicy: amodule.fromsource that isn’t static needs acompositionPolicywhosepullModulepermits its repository. Add the policy or make the source static.module.from: cannot read status.module from the composite resource: module: no such field: the composite resource hasn’t set the field the step reads. Set it, or addmodule.allowEmpty: trueso the step runs nothing until it’s set. The pod logs the skipped step. See Metrics.config.greeting is not a field of config, which has from and allowEmpty only: the step writes the configuration’s value underconfig, as 0.6 took it. The value belongs in the composite resource, in a fieldconfig.fromnames (Input reference).config.from: cannot read spec.config from the composite resource: config: no such field: the composite resource hasn’t set the field the step reads its configuration from. Set it, declare it in the definition, or addconfig.allowEmpty: trueto run the module unconfigured when it’s unset.config.from: spec.config of the composite resource is not an object: the field’s value is a scalar or a list. A module’s configuration is an object, the structure its manifest’sconfig.schemadeclares.module.allowEmpty is set but module.from is not:allowEmptyapplies to a field the composite resource may leave unset and to nothing else. Remove it, or switch the step tomodule.from.apiVersion wasm.fn.crossplane.io/v1 is no longer served; write apiVersion: guestfn.crossplane.io/v1 (the same fields): the Input’s group of 0.6 and earlier, refused byfunction validateunder the step and by the runtime on every request, and warned about byguestfn build. Change theapiVersionline.module oci … is an oci@0.1 module, which function-wasm does not serve; the OCI runtime is function-oci (docs/one-pager-oci-runtime.md), or… is an OCI image with a module manifest (an oci@0.1 module), which function-wasm does not serve …for a step whose reference is a module image: the manifest’s contract isoci@0.1. This package runs WebAssembly components and nothing else. The OCI runtime is a separate package.cannot resolve module: module.type Path is not served by function-oci: an OCI module is an image pulled from a registry, so module.type must be OCI(orHTTP):function-ocipulls images from registries alone. Setmodule.type: OCIwith the module’s pinned reference. The development loop uses a local registry (the OCI runtime).limits.memory 1Gi exceeds the runtime's --module-memory-limit of 512Mi, or the same forlimits.timeoutand--module-timeout: lower the limit or raise the flag.module oci … has an invalid manifest: config.schema: Resource '…' is not present in a registry and retrieving it failed: $ref … is external; config.schema must be self-contained: the module’sconfig.schemareferences a URL or a file. The runtime never fetches a reference. The author inlines the referenced schema. A#/$defs/…reference inside the schema is fine.module oci … config does not match the module's schema: /greeting: got number, want string: the Input’sconfigfails the module’sconfig.schema.
Policy grants
The layers are explained in Cedar policy, and the operator’s side in Grant policy.
-
module oci … requires egress GET to host "x" (requires.egress.http[0]), which the operator policy (--sandbox-policy-file) does not permit: the manifest requests a capability that the layer named in the message doesn’t permit. Variants:… which the compositionPolicy does not permit: the composition layer refuses it.module … requires a private /tmp (requires.filesystem.privateTmp), but the runtime has no --sandbox-policy-file, which is required to grant sandbox capabilities, and the same for env and egress: the runtime has no policy file at all.module oci … requires credential "cmdb" (requires.credentials[0]), which the operator policy (--sandbox-policy-file) does not permit, or… but the runtime has no --sandbox-policy-file, which is required to grant step credentials (spendCredential): the layer has nospendCredentialpermit forCredential::"cmdb".
Add a
permitto the layer named, or mount a policy file. A module that requests less avoids the refusal. -
A module stops seeing a step credential it used to read: the runtime forwards no credential but those a module was granted. Declare it in the manifest, with
requires.credentials: [name]for the whole credential or arequires.envbinding for one key. Then permitspendCredentialfor it in the operator policy, and in acompositionPolicythat scopes the action.function validate --resolvelists what each step’s module receives, and the runtime logs the withheld names at debug level. See Module manifests. -
module … requires.credentials[0]: the request carries no credential "cmdb"; declare it on the pipeline step: add the credential to the step’scredentials. -
the operator policy grants a private /tmp (usePrivateTmp), but the runtime cannot create one under …at startup: pointTMPDIRat a writable directory. AnemptyDirwith asizeLimitalso bounds what a module may write. -
A guest gets
EPERMunder/tmp: the path is outside the private/tmp, the one directory the guest has. -
operator policy …: dialAddress rule "…" must scope the action as == Action::"dialAddress", or another Cedar load error: the--sandbox-policy-fileis malformed and refused at load. AdialAddresscondition accepts nothing butcontext.ip.isInRange(ip("CIDR")),context.ip.isLoopback()or a||of them. -
module oci …: composed apps/Deployment "deployment" (modify), which the compositionPolicy does not permit (composeResource), or… which the operator policy (--sandbox-policy-file) does not permit …, or… composed platform.example.org/WebApp (composite, modify), which …: the module changed a resource that nopermitof the scoped layer matches, and the runtime applied none of its output. Widen the layer named or use a module that composes less. The rules are in the Cedar policy reference. -
module oci …: composed resource "thing" states no apiVersion or kind, so the policy layers cannot judge it (composeResource): a resource the module returned indesired.resourceshas noapiVersionorkindstring. Fix the module. -
module oci …: required core/Secret "db-password" in namespace "team-b" (requirements.resources["db"]), which the compositionPolicy does not permit (requireResource), or… which the operator policy (--sandbox-policy-file) does not permit …, or… required core/Secret with labels team=a,tier=gold (…), which …: the module asked Crossplane for a resource that nopermitof the scoped layer matches. The runtime didn’t relay the ask, and Crossplane didn’t fetch. Widen the layer named or use a module that reads less. The rules are in the Cedar policy reference. -
module oci …: required resource "db" states no apiVersion or kind, so the policy layers cannot judge it (requireResource): a selector the module returned inrequirements.resourcesorrequirements.extra_resourceshas noapiVersionorkindstring. Fix the module.
Signatures
Signing, keyless verification and the trusted root are explained on the Signatures page.
cannot verify module oci …: the operator policy requires a cosign signature, but the runtime has neither --cosign-key nor --cosign-trusted-root to verify it: add--cosign-key. For keyless signatures add--cosign-trusted-rootand atrustSignerrule instead. Or narrow therequireSignaturerule.cannot resolve module: only cosign-signed oci modules are accepted (--cosign-key, --cosign-trusted-root or --cosign-trust-instance is set); http and path sources are refused: the runtime has a signing flag and doesn’t have a--sandbox-policy-file. The runtime then requires a signature of each module, which anHTTPorPathsource can’t have. Publish the module as an OCI artifact, or mount an operator policy whoserequireSignaturerules select the repositories that must be signed. With a policy the refusal readsmodule.http "…" requires a cosign signature (operator policy), but only OCI modules can be signature-verified.cannot verify module oci …: <ref> carries no cosign signature (no Sigstore bundle among its referrers): none of the manifest’s OCI 1.1 referrers is a Sigstore bundle whose subject is this digest. Sign the module with cosign 3. A module signed with cosign 2 alone or with--new-bundle-format=false(asha256-<hex>.sigtag) lands here too: the legacy format isn’t read, so re-sign it.cannot verify module oci …: no valid cosign signature for <ref>: signature does not verify with the configured keys: a bundle exists but no--cosign-keykey signed it. The same list also reportssigned statement's predicate type is "https://slsa.dev/provenance/v1", not https://sigstore.dev/cosign/sign/v1(an attestation),signed statement is for another digestand bundle fetch, size or digest failures.… keyless signature cannot be verified: the runtime has neither --cosign-trusted-root nor --cosign-trust-instance: the signature is keyless. Add--cosign-trusted-rootor--cosign-trust-instance public-good, and atrustSignerrule for the signer. The reverse,key-based signature cannot be verified: the runtime has no --cosign-key, means a key-based bundle met a runtime with a trusted root alone.… keyless signature cannot be verified: the trusted root of <instance> has not been fetched yet (the last attempt failed: …):--cosign-trust-instanceis set and every fetch has failed. The message quotes the last failure. The runtime retries every minute and admits the module once a refresh succeeds, which the log reports asTrusted root updated. For a pod without network, mount the root with--cosign-trusted-root.--cosign-trusted-root and --cosign-trust-instance are mutually exclusive: the file is the trusted root, or the instance's root is fetched over TUFat startup, or--cosign-tuf-refresh must be at least 1m0s: choose the file for an air-gapped pod and the instance for one that can fetch.… keyless signature does not verify against the trusted root: <reason>: the runtime refused the bundle, and the reason is the verification library’s own text. Typical causes are a signature made under a different Sigstore instance, an invalid signature or log promise, or a bundle with neither a Rekor entry nor an RFC 3161 timestamp. Runcosign verifywith the certificate identity and issuer against the same root to tell which.… keyless signature by <identity> (issuer <issuer>) is not trusted for <repository>: no trustSigner rule in the operator policy permits it: the signature verifies but notrustSignerrule covers that signer for the repository. Add or widen a rule for the identity and issuer.
Egress
Egress is explained on the HTTP egress page.
sandbox.egress: <host> resolves to an address the egress policy blocks: the host refuses the ranges of its default block list, which cover the loopback, private, link-local and cluster ranges, and any range adialAddressforbidadds. AdialAddresspermitin the operator policy opens a range for an in-cluster service.sandbox.egress: HTTP egress is not granted to this module: its manifest requires no egress (requires.egress.http): the module made an HTTP request but its manifest doesn’t require egress. Addrequires.egress.httpto the manifest. A Go guest sees the message prefixed withwasmfn:.sandbox.egress: the module's request rate exceeds the egress policy's rateLimit: raise--egress-rate-limit-per-minuteand--egress-rate-limit-burst, or reduce the module’s request frequency.sandbox.egress: the request body exceeds 4194304 bytes (maxRequestBytes): the module sent a request body over 4 MiB, which the host refuses before it asks the policy. Send less in one request.
function-oci modules
cannot load module …: image has neither an entrypoint nor a command: the contract runs the image's configured command (docs/one-pager-oci-runtime.md): the image specifies no command. SetENTRYPOINTorCMDin theDockerfile.cannot load module …: image runs as root (its config sets no user): the OCI runtime runs a process as a non-root user only (docs/oci/modules.md): the image’s process would run as UID 0. Either the image doesn’t set a user, or its user is UID 0 by number or through its/etc/passwd. Set a non-rootUSERin theDockerfile.cannot load module …: image is built for linux/arm64, and this runtime runs on linux/amd64: build for the node’s platform, or push a multi-platform index.cannot load module …: layer is compressed with zstd, which the OCI runtime does not unpack yet; build the image with gzip layers (the default): rebuild the image with gzip layers.cannot load module …: image exceeds the size limit of … bytes (--module-size-limit): the image’s config and layers add up to more than--module-size-limitin the registry. Raise the flag or build a smaller image.cannot load module …: cannot unpack layer 2 (sha256:…): image unpacks to more than 1073741824 bytes, eight times the size limit (--module-size-limit): the image’s layers unpack to more than eight times--module-size-limitbetween them. The runtime keeps the unpacked files in memory while it writes the root filesystem, so it stops reading at the bound. Build a smaller image, or raise--module-size-limit.cannot load module …: cannot unpack layer 2 (sha256:…): image holds more than 1000000 entries, the most the OCI runtime unpacks: the image’s layers contain more than a million files, directories and links between them. Build a smaller image.cannot load module …: cannot unpack layer 2 (sha256:…): layer entry ../etc/passwd has a .. segment, which could name a path outside the image: a layer’s entry has a..segment in its path. Thelayer links … which has a .. segmentform is the same refusal for a hard link’s target. Image builders don’t write such paths. Rebuild the image.cannot load module …: cannot unpack layer 2 (sha256:…): layer entry etc/hosts/x is under etc/hosts, which is not a directory: a layer puts an entry under a path that an earlier entry made a file. The runtime follows a symbolic link to a directory inside the image, and refuses any other parent.a symbolic link that does not resolve: more than 40 links followedin place ofwhich is not a directorymeans the parent is a symbolic link in a loop. Rebuild the image.cannot load module …: cannot unpack layer 2 (sha256:…): layer links bin/sh to bin/busybox, which is not in the image: a hard link’s target isn’t in that layer or in one below it. Rebuild the image.cannot load module …: cannot unpack layer 2 (sha256:…): layer entry .guestfn/config.json is at /.guestfn/config.json, which the OCI runtime keeps for the image config it resolved: the image has a file at the path where the runtime stores its own copy of the image config. Remove the file from the image. The runtime also refuses anything other than a directory at/.guestfn.module … requires egress (requires.egress.http), which function-oci does not serve yet: the VM has no network device (docs/one-pager-oci-runtime.md): function-oci has no egress yet. Removerequires.egressfrom the manifest.module … failed: process exited with status 1 before answering the call: <line>: the process ended before it answered, and the line is the last one it logged. An SDK server without--insecureends this way: check the manifest’soci.args.module … failed: run returned an error: <message> (gRPC status <code>): the function answered the call with an error.module … failed: run failed: the guest did not connect before the deadline: the VM booted but its init never reached the host: the runtime failed before the module ran.--debuglogs the VM’s console, which says how far the boot got. A console that ends withguestfn-init: cannot mount "squashfs" "/dev/vda" on "/lower": Invalid argument (os error 22); the root filesystem is a squashfs packed with zstd, which the guest kernel has to read (CONFIG_SQUASHFS and CONFIG_SQUASHFS_ZSTD)means the kernel--guest-kernel-pathnames was built without zstd for squashfs: every run then fails this way, at its deadline. Use the kernel the package includes, or build yours with both options.
Runtime and startup
cannot create cache directory /tmp/guestfn-cache: …at startup: the pod’s filesystem there can’t be written. Mount anemptyDirat that path through aDeploymentRuntimeConfig.cannot open /dev/kvm: No such file or directory; the OCI runtime boots a microVM per request and needs the device granted to its pod (docs/oci/install.md)atfunction-oci’s startup: the pod has no/dev/kvm. Request it from a device plugin, as the OCI runtime page documents. WithOperation not permittedin place ofNo such file or directory, the pod mounts the device as ahostPath, which doesn’t admit it; withPermission denied, the device is admitted and the pod’s user isn’t in its group: the same page has both fixes. The pod restarts until the device is there, and every request meanwhile fails with Crossplane’sno children to pick from.module … failed: waiting for a run slot: deadline exceeded, or the step-slot and run-memory forms: the request’s deadline passed while it waited for a bound, so nothing ran. Raise the bound, shorten runs, or watchguestfn_module_runs_in_flight(see Metrics).cannot load module … : compile exceeded --module-compile-timeout 5m0s: a cold load (fetch and compile) ran past the bound. The compile finishes on its own and stores its artifact, so the next request for that digest is served; a module that hits the bound every time is too large to compile under it, so raise the bound or lower--module-size-limit.- The first request is slow, later ones are fast: expected, because the compile happens once per module digest per process. A volume under
/tmp/guestfn-cachespares the next process the fetch, not the compile, which--warm-modulesmoves ahead of readiness. See the cache section of Runtime flags. Cannot warm moduleat startup: a--warm-modulesentry didn’t load, and the log line gives the entry and the reason. The pod serves anyway and loads that module on its first request.cannot snapshot the VM; booting itorcannot restore the VM's snapshot; booting itinfunction-oci’s log, under--enable-vm-snapshots: the runtime couldn’t make or restore an image’s snapshot, and the line’serrorhas the reason. The run booted its VM, so the request was served. That image runs without snapshots until the runtime loads it again. A snapshot writes a file as long as the VM’s memory under/tmp/guestfn-cachebefore the runtime rewrites it sparse, so check that the cache has that much room. At warm-up the same failure readsWarmed module, but the engine could not make its first run ready.- The readiness probe fails for a while after start: the pod is warming
--warm-modules. See Readiness. rpc error: code = Unavailable desc = the function is not readyon a composite resource: the step called a pod that hadn’t finished warm-up. Crossplane retries, and the error clears once the pod is ready. A readiness probe on/readyzkeeps such a pod out of the Service until then.
Guest ABI v2
This page is for people who write a guest toolchain or its glue. It states what the runtime requires of a module and what it provides, so you can build to the contract to the letter. It assumes you know WIT and the component model; to write a function, start at Write a module. Grants are on Cedar policy, the Input on the Input reference and the manifest on Module manifests.
A guest is a WebAssembly component targeting a world of the WIT package guestfn:function@1.0.0 (wit/guestfn-function.wit). The payload is Protobuf: RunFunctionRequest bytes in, RunFunctionResponse bytes out. The canonical ABI moves memory, so a guest has no allocator export. ABI v2 is the one ABI the runtime serves.
The world
package guestfn:function@1.0.0;
world function {
enum log-level { debug, info, warn, error }
import log: func(level: log-level, msg: string, kv: list<tuple<string, string>>);
export run: async func(request: list<u8>) -> result<list<u8>, string>;
}
runhandles one request. The host passes the caller’sRunFunctionRequestand returns the guest’sRunFunctionResponse. It decodes and encodes each of them once on the way and keeps every field, including one newer than the runtime’s own copy of the proto, on every message of the function API. The bytes aren’t the caller’s or the guest’s own, so a guest can’t depend on their layout. The host leaves out the step credentials the module wasn’t granted, and the pull credential in every case.runisasync, so a guest may await its imports,wasi:httpamong them. The run’s deadline applies while it does, less the time it waits for the host’s HTTP answer. A sync-liftedrunalso satisfies the world, because the canonical ABI accepts a sync function where an async one is expected.logis structured logging through the host, with typed values. The host attaches the module’s identity to every line and renders it at the runtime’s level of the same name.debuglines appear under--debugalone.- The runtime typechecks
log-levelto the letter, sologchanges with2.0.0alone. function-sync, the package’s second world, is this contract withrundeclared sync, for a toolchain that can’t async-lift it. The runtime checks every guest againstfunction.
WASI and the sandbox
The world doesn’t import WASI. A guest brings whatever its toolchain emits, and the host links both WASI generations:
- WASI 0.2: components built by jco, componentize-py or Rust’s
wasm32-wasip2, and a guest that importswasi_snapshot_preview1, the Go scaffold’s, through the wasip1 adapterguestfn buildlinks in. - WASI 0.3: a
wasm32-wasip3build.
The engine accepts WebAssembly 2.0 plus the extended-const and
relaxed-simd proposals. Relaxed SIMD runs with its deterministic semantics,
and a module computes the same result on every host. The engine refuses the
other WebAssembly 3.0 proposals at compile: threads, GC, function references,
exceptions, tail calls, multi-memory and memory64. No guest toolchain in the matrix emits any of
them (every scaffold and example was measured with wasm-tools validate on
2026-10-28), and a proposal can be enabled later as a minor.
The sandbox allows:
- no network sockets;
- no filesystem beyond the granted private
/tmp, the one pre-opened directory; - environment as granted, with nothing added;
argvis["function"].
The three-layer decision grants these capabilities. limits and the deadlines apply to every run. limits.timeout bounds the time of a run, not counting the time it waits for the host’s HTTP answer. The request’s gRPC deadline is the hard cap. Sleeping or blocking in another WASI call spends that budget too, and the run ends at the deadline whether the guest is executing or not. A component has no top-level memory export, and the host reserves nothing from --max-total-run-memory before the run. It charges the whole footprint as the guest claims its memories, and a growth the pool can’t serve fails inside the run: memory.grow returns -1.
HTTP egress
A guest sends HTTP requests through wasi:http/client@0.3.0 (send: async func) or wasi:http@0.2’s outgoing-handler, which componentize-js’s fetch() uses. One host bridge serves both. The runtime’s egress client performs each send or refuses it under the grant. The policy is on HTTP egress.
- Bodies are complete on both sides, and the response budget applies to whole responses.
- The guest receives a host-reported failure as the
internal-errorcode, whose payload is the refusal string, for a grant refusal, a blocked address, an exhausted budget or a transport failure. The wording is contract, held by the conformance goldens. - The time a guest waits for the host’s HTTP answer is credited back to its deadline.
Errors
A guest that can produce a response encodes failures into it as a fatal Result. run returning err(string) is for failures before a response can be built, such as a codec that can’t decode the request. The host turns it into the request’s fatal result: module <desc> failed: run returned an error: <string>.
Traps, WASI exits, deadline interrupts and memory denials are fatal results from the host that name the module, never gRPC errors:
run failed: trap: …run failed: module exited with status Nrun failed: module exceeded its execution deadline (…)
Detection
The runtime reads the binary format from the first eight bytes of the module. A component (layer 1 in the WASM header) is loaded and typechecked against the world. A core module (layer 0) is refused with one sentence, whatever it exports:
module is a core module, which function-wasm 1.0.0 no longer runs (ABI v1 was removed); build it as an ABI v2 component (docs/abi-v2.md)
The runtime reports it as a fatal result (cannot load module <desc>: …), and guestfn build, guestfn inspect and function validate --resolve print the same sentence. Detection has no flag and no Input field.
A typecheck refusal begins component does not implement the guestfn:function@1.0.0 world: ….
A module manifest declares contract: wasm@1.0, this world. Another version is refused before the module is looked at: contract wasm@0.9 is not one the wasm engine implements: wasm@1.0.
Versioning
guestfn:function@1.0.0 is the contract from function-wasm 1.0.0 on. The world’s version moves on its own, by what a change asks of guests:
- A 1.x minor may add imports and nothing else: a new interface or a new function. A component imports what it uses and nothing more. The runtime serves a guest built against an earlier 1.x unchanged. A guest that imports the addition declares the contract minor that added it, and a runtime that doesn’t offer that contract refuses it by name.
- Within 1.x,
run’s signature, thelogimport (thelog-levelcases included) and anything else already in the world stay as they are. Changing or removing any of them is2.0.0, a world every guest is rebuilt against. - A new field of
RunFunctionRequestorRunFunctionResponsemoves no world version. Payload evolution is Protobuf’s.
A guest declares the WASI 0.2 or 0.3 interfaces it imports in wit/world.wit, at the versions the wasmtime-wasi-http release the runtime builds on links. The release notes list the WASI versions the runtime links. A guest built against an older set keeps running while those versions are linked, and otherwise fails the world typecheck at load.
Getting the world
Guest toolchains read a local wit/ directory, so guestfn build fills it. A guest commits wit/world.wit and guestfn.lock, which pins the digest of every package the guest builds against, and wit/deps/ stays out of version control.
The guest’s own world, wit/world.wit in a local:guest package, includes one of the two worlds beside whatever else the guest imports:
package local:guest;
world function {
include guestfn:function/function-sync@1.0.0;
import wasi:http/outgoing-handler@0.2.12;
}
guestfn init writes both files. The rust scaffold includes function. The go, ts and python scaffolds and the C, C++, Zig, Odin, MoonBit and C# examples include function-sync, the signature their toolchains take today.
Publication
Publish WIT (publish-wit.yml), run by hand from a wit-v<version> tag, publishes the package, signed and attested, as an OCI artifact in the CNCF Wasm OCI layout, the format of wkg: ghcr.io/jonasz-lasut/guestfn/function:<version>. A published version is never pushed again.
guestfn wit update bumps a guest to a published version. It installs the newest version of the major the guest’s include declares, or the version --version names, and moves the version in the include in wit/world.wit. It also writes the WASI packages the world imports, at the versions the world declares, and everything those refer to, from ghcr.io/webassembly/wasi. guestfn.lock pins every package’s digest. Regenerate any bindings you check in afterward. --dir names the project, and --repository and --wasi-repository name mirrors.
With a guestfn.lock present, guestfn build pulls the pinned digests, no others, into wit/deps/ before it calls the toolchain, and a copy that changed is written back. guestfn wit fetch does the same for a build that doesn’t go through guestfn build. A project with no lock keeps the copy it has.
To fetch the package with wkg instead, map the namespace in its configuration:
[namespace_registries]
guestfn = { registry = "guestfn", metadata = { preferredProtocol = "oci", "oci" = { registry = "ghcr.io", namespacePrefix = "jonasz-lasut/" } } }
wkg get guestfn:function@1.0.0 --format wit then writes guestfn_function@1.0.0.wit, the file a guest that doesn’t use guestfn keeps under wit/deps/.
Compatibility
This page is for anyone who depends on function-wasm across releases: composition authors, operators and module authors. It lists what’s stable throughout 1.x, what a minor release may add and how a removal is announced. function-oci, the OCI runtime, is alpha and has a section of its own, function-oci at 0.x.
What a Composition, a flag, a dashboard or a CI job relies on keeps working on every 1.x release, with one exception: a minor release may add a refusal for a rule that didn’t exist before.
What’s stable
- The Input,
guestfn.crossplane.io/v1: its field names, types and semantics. A field the runtime doesn’t know is ignored, andfunction validatewarns naming it; the removedpolicyandsandboxfields it refuses by name.configis an object offromandallowEmptysince 0.6 (#262): a value written there is refused, and the refusal states the field it belongs in. - Each runtime flag’s meaning and default.
- The wording of refusals and fatal results, as the conformance goldens pin
it (
crates/function/testdata/conformance/). Operators grep logs and XR conditions for these strings. - The module manifest (
guestfn.yaml): its fields and what each requests. - The ABI v2 world, which has its own version (see ABI v2).
- The metric names and labels (
guestfn_*,grpc_server_*). - The cache directory,
/tmp/guestfn-cache, where an operator mounts a volume or anemptyDir. function validate: its exit codes (0 admitted, 1 refused, 2 the tool failed) and the field names of--output json.- The
guestfncommands, their arguments and flags.
The log line layout, the on-disk cache format and when a sweep runs aren’t on the list, so they aren’t promised.
Minor and major releases
A minor release may add to the list without changing what’s already on it: new Input fields, flags, manifest fields and metrics, and refusals for rules that didn’t exist. It may also widen what’s accepted, so a document one release refused is admitted by the next.
Removing or renaming anything on the list takes a major release, after the deprecation below, and so does changing a pinned wording or a default or narrowing what’s accepted.
Patch releases
A patch is a release for fixes, and it changes nothing on the list, with one exception: a security fix may narrow what’s accepted. Such a patch can refuse a document or a policy that the release before it admitted, where the defect is that the runtime admitted it. function-wasm 1.0.1 did so: it reads a registry into one canonical form, and it refuses a policy that specifies a repository in another spelling.
The notes of such a patch list every change of this kind in their “Before you upgrade” section, with the refusal as the runtime prints it and what to write instead. A patch doesn’t narrow anything for another reason, and it doesn’t remove or rename what’s on the list.
Deprecation policy
A removal runs in two steps:
- The next release deprecates it. A deprecated thing keeps working for at
least one minor release.
function validatewarns under the steps that use it, and the runtime logs one line per load or request that does. - The next major release removes it.
ABI v1 set the precedent: deprecated in 0.6.0, removed in 1.0.0. Before
1.0 a rename may skip the deprecation step: the Input’s group moved from
wasm.fn.crossplane.io to guestfn.crossplane.io outright, and the
runtime refuses the old group by name. The project’s own names moved the
same way at 0.6, with no alias for the old ones: the metric series
function_wasm_* became guestfn_*, the cache directory
/tmp/function-wasm-cache became /tmp/guestfn-cache and the stamped
version variable FUNCTION_WASM_VERSION became GUESTFN_VERSION.
function-oci at 0.x
function-oci runs an OCI image in a Firecracker microVM (Install function-oci). It’s alpha and 0.x, and function-wasm’s 1.x promise doesn’t extend to it. Until function-oci’s own 1.0.0, a release may break anything the package has. A release that renames or removes something refuses the old name by name, with no deprecation step. The design record keeps the alpha label until the contract and the engine’s flags have held through two minor releases (OCI runtime).
What function-oci shares with function-wasm is the Input, the module
manifest and the guestfn_* metric names. Whether those are stable for
function-oci isn’t decided while function-oci is at 0.x. Its own 1.0.0
decides it.
oci@0.1 is the contract an image follows
(OCI modules). The image’s command starts
a FunctionRunnerService gRPC server on port 9443, and the runtime calls
RunFunction on it once per request, as the image’s configured user, in
its configured working directory, with its configured environment plus the
requires.env bindings the module was granted. The process’s output is its
log: a line that’s a JSON object with level and msg logs at that level,
and any other line logs at info. An answer is a run, and any other ending
is a fatal result on the step.
A module’s manifest declares the contract it follows, contract: oci@0.1,
and function-oci refuses a version its engine doesn’t offer. The contract
has a version of its own, and while it’s 0.x a minor version may break
images built for the one before
(Module manifests). Its stability starts
at oci@1.0, with function-oci’s 1.0.0.
The wording of a fatal result isn’t part of the contract. oci@0.1 says
what an ending means, and the sentence that reports it, such as process exited with status <n>, may change in any release. The conformance
goldens pin none of function-oci’s sentences.
Among what a 0.x release may change:
- The engine’s flags and their defaults:
--vmm-binary-path,--guest-kernel-path,--guest-init-pathand--vm-vcpus(Install function-oci). - The wording of the engine’s fatal results and of the refusals that function-oci alone prints.
- The metrics that function-oci alone emits:
guestfn_module_snapshot_duration_seconds, and thesnapshotvalue of thecachelabel onguestfn_module_cache_events_total. - Alpha features behind flags of their own, VM snapshots among them (Per-image microVM snapshots).
Development
This page is for contributors to guestfn. It lists the commands that build, test and lint a change, and says which of them CI runs for you. It assumes a checkout with a Rust toolchain.
Commands that run on every push
CI runs these on every push, and on a pull request that changes code. A
pull request that touches documentation alone skips them: docs/, the
top-level, package and example Markdown files, .claude/ and extensions/.
cargo build --workspace && cargo test --workspace
cargo fmt --all --check && cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo deny check advisories bans licenses sources # cargo install cargo-deny --locked
git ls-files '*.sh' | xargs shellcheck && actionlint # both on your PATH
The tests include the conformance goldens and the scaffold goldens. The
cargo deny run checks Cargo.lock against deny.toml: every crate is
free of published advisories, under an allowed license and from crates.io.
The last line lints the shell scripts and the workflows. actionlint also
passes each run: block of a workflow through shellcheck, and
.github/actionlint.yaml is its configuration. A pull request that touches the documentation (docs/, README.md, SECURITY.md or book.toml) also runs Vale, after a check that the design records index and docs/SUMMARY.md restate the status line of each one-pager:
make vale
Commands that run on demand
These need Go, Docker or kind on your machine:
(cd examples/function-wasm-go && go test ./...)
make -C examples/function-wasm-go render
make e2e
The first line tests the Go example and its vendored internal/wasmfn glue. The second is the development loop. The third runs the end-to-end suite in a kind cluster. Testing explains the two tiers and the e2e: labels that select the end-to-end scenarios on a pull request.
(cd examples/function-oci-go && go test ./...) tests the OCI example natively. make oci.test runs the suite of the OCI engine in real VMs and needs /dev/kvm.
Guest toolchains
The workspace tests build every scaffold (what guestfn init writes) to WebAssembly and run each through the host. The tests skip a scaffold whose toolchain isn’t on PATH, so an all-green run can mean a guest never ran. The toolchains are go, cargo and rustup for the rust scaffold’s pinned toolchain (which also needs protoc), npm and python3. Set GUESTFN_REQUIRE_TOOLCHAINS=1 to make a missing toolchain a failure.
Where to go next
Testing says where a new test goes. AGENTS.md describes the source layout and conventions. Design records lists the design documents.
Testing
This page is for contributors adding or changing a test. It says which of the two test tiers a change belongs in and how to run the end-to-end suite on your machine. It assumes a Rust toolchain for the first tier and Docker for the second.
crossplane render belongs to the
development loop and isn’t part of either tier.
| Tier | Runs | What it covers |
|---|---|---|
| unit and component | cargo test --workspace, on every push and on a pull request that changes code | the engine, the runtime and function validate against in-memory stand-ins and recorded goldens, and every scaffold built and run through the host (the guest suite) |
| end-to-end | make e2e, an e2e: label on a pull request, the release matrix on a release branch | each function’s package installed by Crossplane in a kind cluster, as an XR author and an operator see it |
On your machine, two suites of the first tier skip what the machine can’t
run. The guest suite skips a guest whose toolchain isn’t installed, and the
VM suite of the OCI engine skips every test without KVM and its tools. The
harness still reports a skipped test as ok. Each one prints a SKIPPED:
line with its name, the reason and the number of tests skipped so far. CI
sets GUESTFN_REQUIRE_TOOLCHAINS and GUESTFN_REQUIRE_KVM, which turn a
skip into a failure.
The tier for a new test
| The change | The test |
|---|---|
| a guest-visible behaviour of the engine (a trap, a limit, a WASI interface) | a WAT fixture in crates/engine-wasm/tests/engine.rs, or a setting of the committed guest driven from crates/engine-wasm/tests/committed_guest.rs |
| an Input rule, a refusal, a policy decision | a unit test beside the code, a fixture under crates/function/testdata/validate/ and a conformance golden |
| a scaffold change | the template, then UPDATE_GOLDENS=1 cargo test -p guestfn; the guest suite builds the goldens |
| a fixture or stand-in a test needs | guestfn_engine_wasm::testing for a guest component, guestfn_runtime::testing for a registry, a signer, an in-process runtime, a server or a policy (both behind the testutil feature) |
something that Crossplane alone shows, such as a condition, an event, a resolved requirements entry, a pod restart or a scraped metric | a feature in the end-to-end suite |
UPDATE_GOLDENS=1 cargo test -p function-wasm --test conformance records a
conformance golden. A re-record is a behaviour change, so say so in the commit.
A suite uses the shared testing modules and never declares its own copy of a
fixture.
The end-to-end suite
The suite is in crates/e2e (package guestfn-e2e). It gives each
test its own namespace (with_temp_ns in crates/e2e/src/ns.rs) and uses typed
kube-rs helpers. Tests wait with timeouts and compare what the cluster contains with
assert_eq!. The crate is empty without its cluster feature, so
cargo test --workspace builds none of it.
The cluster
make e2e.up provisions the cluster before the tests. It uses the Crossplane build submodule’s make library (build/makelib, with
pinned kind, kubectl, helm and crossplane CLI under .cache/tools) and
the suite’s own setup binary, in three steps:
controlplane.upcreates a kind cluster (KIND_CLUSTER_NAME, defaultfunction-wasm-e2e) with Crossplane atCROSSPLANE_VERSION. The Makefile’s default is the current Crossplane release, which Renovate moves, and the environment overrides it.e2e.crossplanethen waits for the Crossplane deployment and its package CRDs.e2e-setup(crates/e2e/src/bin/setup.rs) creates thee2enamespace and aregistry:3behind Basic auth and TLS from a CA it generates. It installs provider-nop (PROVIDER_NOP_VERSION), a provider whoseNopResourcemanaged resources do nothing, so the tests can compose resources without a cloud. It pushes and signs the test module under every variant and creates the profiles’ ConfigMaps, Secrets, volume andDeploymentRuntimeConfigs incrossplane-system. When the kind node has/dev/kvm, it installs the KVM device plugin and puts the node’skvmgroup into theociruntime config as a supplemental group. It then creates the Guest XRD and writes_output/e2e/state.json, which the tests read.make e2e.imagebuilds the runtime image fromcrates/function-wasm/Dockerfile, or fromcrates/function-wasm/Dockerfile.devaround a prebuilt binary named byFUNCTION_BIN.xpkg.build.function-wasmbuilds the Function package from it, andlocal.xpkg.deploy.function.function-wasminstalls it from Crossplane’s cache withpackagePullPolicy: Never, on thewasmruntime’sdefaultprofile.function-ocifollows the same way, fromcrates/function-oci/Dockerfilein Docker or fromcrates/function-oci/Dockerfile.devaround the prebuilt piecesFUNCTION_OCI_TOOLSnames, on theociruntime’sdefaultprofile.E2E_OCIdecides:auto(the default) installs it when the kind node has/dev/kvm,1requires it and0leaves it out, the two values CI’s profile jobs set.E2E_WASMdecides the same forfunction-wasm:1(the default) installs it and0leaves it out, which CI’sociprofile jobs set. Each profile job installs its own runtime alone. Setup pushes every variant either way (theocisuite’s wrong-type case names thewasmruntime’splainvariant) and writes thewasm/defaultpolicy either way (theociprofile’sDeploymentRuntimeConfigmounts it);0skips the package, thewasmprofiles’ runtime configs and the lifecycle cache volume. The test module as a process is built in arustcontainer on any host but Linux.make e2e.upbuilds it every time, andcargorebuilds what changed and nothing else. A path given inE2E_OCI_GUESTnames a prebuilt binary, whichmake e2e.upuses unchanged.
make e2e.wasm-profile.<p> and make e2e.oci-profile.<p> run one profile’s
tests, make e2e.test.wasm and make e2e.test.oci one runtime’s,
make e2e.test every profile the cluster has, make e2e.down deletes the
cluster and make e2e does everything. After a failed run, make e2e.dump writes the cluster’s state under
_output/controlplane-dump. A failed test also keeps its namespace and dumps
its objects, events and the function pod’s log under
_output/e2e/logs/<namespace>.
The profiles
A profile is one runtime configuration, flags and an operator policy with the
mounts they need, for one of the two runtimes. wasm and oci are each an
installed Function. Each test binary (crates/e2e/tests/<runtime>_<profile>.rs)
switches its runtime’s Function’s runtimeConfigRef to its profile’s
DeploymentRuntimeConfig (crates/e2e/profiles/<runtime>/<profile>/drc.yaml)
before its first test and waits for the rollout. Each binary uses one profile.
| Profile | What it tests |
|---|---|
wasm/default | every case a runtime admits, under both signature verifiers |
wasm/strict | the refusals of a narrow operator layer, the read fence’s ceiling among them |
wasm/lifecycle | warm-up, the caches across a restart and the trusted root over TUF |
oci/default | the function-oci package (the OCI runtime) beside function-wasm, running the test module as a process in a Firecracker VM, and the published function-oci-go example. Its runtime config mounts the wasm/default policy |
oci/privileges | not a profile of its own: a second suite on the oci/default runtime config. Its tests cover the refusal of an image that runs as root, the process’s empty capability sets, fifteen privileged operations the kernel denies, and a setuid copy of the binary that runs as the image’s user |
oci/snapshots | the oci/default profile with --enable-vm-snapshots and the published function-oci-go warmed. Its tests cover the snapshot the warm-up takes, runs restored from a snapshot, eight Guests restoring it at once, and an env binding in a restored process |
The default profile runs the runtime with --cosign-key (the suite’s key)
and --cosign-trusted-root (the in-memory Sigstore instance’s root merged with
the public-good root). Its policy requires signatures from the suite’s registry
and the published examples, and grants the egress, credential, env and private
/tmp cases the tests need. The policy is crates/e2e/profiles/wasm/default/policy.cedar
and the tests are in crates/e2e/tests/wasm_default.rs.
The strict profile has no verifier. Its policy requires a signature for the
plain variant alone and grants egress to the registry host with no
dialAddress hole. It also scopes requireResource to the tenant’s own
namespace. Its tests cover the no-verifier refusal, the block list refusing
the service CIDR in band, the env, credential and /tmp refusals, and the
operator ceiling refusing a cluster-scoped read.
The lifecycle profile runs with --debug, --warm-modules on the published
function-wasm-go, a PVC-backed cache bounded below that module’s size, a readiness
probe on /readyz, and --cosign-trust-instance public-good with no root file
mounted. Its policy requires the published examples’ signatures and accepts
this repository’s Publish Examples workflow as a signer. Its tests cover readiness
waiting for the warm-up, the caches across a restart, and the trusted root
fetched over TUF from the real public-good repository.
The test module
crates/e2e/guest is the one module the suite drives: a Rust ABI v2 guest in
its own Cargo workspace, reading the rust scaffold’s wit/ and proto/ in
place. make e2e.guest builds it on the scaffold’s pinned
toolchain and the result is committed as fn.wasm. The build embeds the
machine’s paths. A rebuild never matches the committed file byte for byte.
make e2e.guest also writes fn.wasm.stamp, a digest of the module’s sources
and of the module, and crates/engine-wasm/tests/committed_guest.rs fails
when either differs from the tree. Edit the module’s source, then run
make e2e.guest and commit both files. The stamp leaves Cargo.lock out, so
a dependency update that changes the lock alone doesn’t need a rebuild.
The Guest XR is the composite resource the suite creates for each test, and its
spec says what the module exercises:
| Field | What the module does |
|---|---|
nopResources, readyAfterSeconds | composes that number of provider-nop NopResources, Ready after the delay, and marks each ready once its observed counterpart is |
egress.url | sends a GET request to the URL through wasi:http and writes the status and body, or the host’s refusal, to status.egress |
env, credentials | writes those variables and the keys of those step credentials to status |
privateTmp | writes and reads back a file under /tmp, reporting the outcome |
requirements.environmentConfig | asks Crossplane for that EnvironmentConfig and echoes its data once resolved; the cluster cases of the read fence permit and refuse that ask by kind |
privileges | as a process, tries what a Linux capability would allow and runs the setuid copy of its binary, reporting each outcome |
fatal, spin, growMiB | a fatal result with the message, a spin past the deadline, a memory growth refused at the limit |
A variant is the same fn.wasm published under one manifest. The suite has
nine, one for each of the six manifests in crates/e2e/guest/manifests/wasm,
plus three signature variants derived from the plain one; the oci profile’s
variants are the same declarations under manifests/oci, around the module
as a process. One of them, oci-root, is built on an image that doesn’t
set a user, which the runtime refuses at load. Each has its own digest,
because the runtime caches a signature verdict per repository and digest, and
two variants sharing both would share a verdict. The same fn.wasm is the engine’s wasi:http fixture
(crates/engine-wasm/tests/committed_guest.rs).
Running it locally
make e2e.up # kind, Crossplane, provider-nop, the registry, the packages (Docker running; function-oci when the kind node has /dev/kvm)
make e2e.wasm-profile.default # or strict, lifecycle; e2e.oci-profile.default with function-oci installed
make e2e.down
cargo test -p guestfn-e2e --features cluster --test <runtime>_<profile>
runs one profile as the make target does.
FUNCTION_BIN=<linux binary> make e2e.up wraps a prebuilt runtime with
crates/function-wasm/Dockerfile.dev instead of compiling the workspace in the
build stage of crates/function-wasm/Dockerfile, as CI does. After controlplane.up, KUBECONFIG and the
current context point at the cluster. CROSSPLANE_VERSION=2.2.7 make e2e runs
the whole suite on another Crossplane, given as the chart version without a
v. 2.2.7 is also the release matrix’s oldest pin.
The workflows
ci.yml runs lint with --all-features and cargo test --workspace on every
push, and on a pull request unless it touches documentation alone: docs/,
the top-level, package and example Markdown files, .claude/ and
extensions/. The rule goes by path, since a Markdown or JSON file under
crates/ is a fixture, a golden or a template.
Two more jobs run the cargo test targets that need tools of their own:
guest-suiteruns the guest suite on every such change, withGUESTFN_REQUIRE_TOOLCHAINS=1so a missing toolchain fails instead of skipping. The scaffolds don’t have lockfiles, and an upstream release that breaks one fails this job on every pull request. The suite also runs the unit tests andcargo clippyof the end-to-end test module, a Cargo workspace of its own thatcargo test --workspacedoesn’t reach.vm-suitebuilds the init and the fixture (musl), fetches the pinned Firecracker and kernel (make oci.tools) and runs the suite of the OCI engine in real VMs under the runner’s KVM (GUESTFN_REQUIRE_KVM=1: a missing tool fails instead of skipping). On a pull request it runs when the change touches the OCI engine, the init, the protocol, the fixture,crates/engine, the dependencies or the Firecracker and kernel pins.
e2e.yml runs on a pull request’s own events: when it opens, on every push
to it and when someone adds a label. The labels on the pull request select
the scenarios:
| Label | Runs |
|---|---|
e2e:all | every scenario below |
e2e:wasm:all | every wasm scenario |
e2e:wasm:default, e2e:wasm:strict, e2e:wasm:lifecycle | one wasm profile |
e2e:wasm:examples | the build (<lang>) jobs of the WebAssembly examples |
e2e:oci:all | every oci scenario |
e2e:oci:default, e2e:oci:privileges, e2e:oci:snapshots | one oci profile |
e2e:oci:examples | build (oci-go) |
A pull request with more than one of these labels runs their union. A
labelled pull request runs again on every push until the label is removed,
and a newer commit cancels the run of the one before it. A pull request
without an e2e: label doesn’t run a scenario.
The select job reads the labels and calls two reusable workflows.
e2e-wasm.yml has the scenarios of function-wasm:
build-toolscompiles the runtime andguestfnonce- one
e2e (<profile>)job per selected profile, each on a kind cluster of its own at the Makefile’sCROSSPLANE_VERSIONwithfunction-ocileft out (E2E_OCI=0). The profiles run side by side, and a failed job uploadsmake e2e.dump - one build job per example toolchain: build, unit tests, lint, and codec and
bindings drift, each module wrapped by the
guestfnthatbuild-toolscompiled. A drift check runs the pinned generator again, thenhack/check-generated.sh. The script fails on any difference from the committed files except the version a Protobuf generator writes in the header of a generated file. An update of protoc, protoc-gen-es or nanopb that changes nothing else passes. One that changes the output fails until someone commits the result, and so does every wit-bindgen update, since the bindings are compared whole
e2e-oci.yml has the scenarios of function-oci:
build-toolscompilesfunction-oci, the init and the test module as a process (musl) and fetches the pinned Firecracker and kernel (make oci.tools)- one
e2e (<profile>)job per selected profile, each on a cluster of its own withfunction-ocialone (E2E_WASM=0 E2E_OCI=1) build (oci-go)vets and tests the process guest and builds its image, pushing nothing
The workflow doesn’t post a comment or a commit status, because every job is
already a check on the pull request with a link to its run. One job,
e2e-gate, is the check the ruleset on main requires. It starts with the
run and stays in progress until the scenarios have ended, so the commit
doesn’t count as passed on an earlier run’s result while a run is still
going. It then ends as the e2e-verdict job did. That job passes when no scenario was
selected or every selected one passed. It fails when a selected scenario, or
a build that scenario waited for, failed or was cancelled. On a labelled pull
request a new commit can’t clear a failure, because the push starts the run
again. The workflow reads the labels the pull request has when the run
starts, so starting an old run again selects the current labels.
Any label starts the workflow, an unrelated one such as kind:bug too. That
run takes a concurrency group of its own, which keeps it from cancelling a
run in progress, and it doesn’t run a scenario. Its e2e-verdict looks up
the verdict the head commit already has
(the latest e2e-gate check that ran to an end) and repeats it, so an
unrelated label can’t replace a failure with a pass. With no verdict yet it
passes, unless the pull request has an e2e: label: the run that owes the
verdict is then still going, and this one fails until that run’s gate
replaces it.
A pull request’s run uses the pull request’s own copy of the three workflow
files, so a change to them is exercised before it merges, and
.github/CODEOWNERS names the owner as the code owner of
.github/workflows/ for that reason. A pull request from a fork gets a
token that can’t write, without secrets, which is all the jobs use.
Every job of every workflow has a timeout-minutes, so a hung cluster, VM
or download ends its job.
A pull request’s run restores caches and saves none, as in ci.yml. A
second workflow, e2e-caches.yml, saves them on main and
never runs on a pull request. It
calls the same two reusable workflows without a profile, which runs both
build-tools jobs and every example’s build job without a cluster, and its
seed-suite-cache job compiles the end-to-end crate under the key every
profile job restores. Because the jobs that save a cache are the jobs that
restore it, the keys can’t drift apart.
A cache key reads the compiler, the runner and the dependency files, never
the sources, so a push to main runs the builds whose key it can have
changed and skips the rest. The workflow’s changes job lists the files the push touched. A
manifest, a lockfile or a toolchain file among them selects the builds that
read it: the Rust builds, the WebAssembly examples or the process guest. A
push that touches none runs nothing.
One run a day builds everything and saves the keys that are missing. It
covers what no push changes: a new stable Rust or runner image, and a cache
GitHub evicted after a week unread. The release matrix restores main’s
caches and saves none.
GitHub’s Linux runners expose /dev/kvm to a udev rule the OCI jobs and
the legs of the release matrix install, and the kind node inherits it. The
node’s device is root:kvm 0660 whatever the rule says, and the pod’s user is
the package’s. The suite’s setup installs the device plugin
(crates/e2e/cluster/kvm-device-plugin.yaml), reads the node’s kvm gid and
puts it into the oci runtime config as the supplemental group of the pod: the
recipe on the operator page for a hosted cluster. The same page says why a
hostPath mount of the device isn’t enough. A
failed profile job prints the description and logs of every function pod into
the job log (make e2e.dump does that before the dump itself).
The release matrix
Crossplane maintains its three most recent minor releases (release cycle), and the function supports the same three. A pull request’s end-to-end run tests the current minor, and the matrix adds the two before it.
release-matrix-e2e.yml runs on every push to a release-function-wasm-X.Y
or release-function-oci-X.Y branch, and the branch’s name says which
function it tests. Its plan job reads the runtime from the name and calls
that runtime’s reusable workflow, e2e-wasm.yml or e2e-oci.yml, once with
the three Crossplane versions. The runtime is built from the branch once, and
every profile runs on a kind cluster of its own per version: nine jobs in
parallel, each uploading the cluster dump when it fails. A function-wasm
branch doesn’t run a VM or an oci profile, and a function-oci branch
doesn’t run a wasm profile: the branch doesn’t release what those test. A red job
blocks the release.
gh workflow run "Release Matrix E2E" --ref <ref> -f runtime=<wasm|oci> runs
it by hand on any ref.
The Makefile’s CROSSPLANE_VERSION default names the current version. The
workflow’s env (CROSSPLANE_PREVIOUS, CROSSPLANE_OLDEST) pins the latest
patch of the two older minors. A red version blocks the release: the release
process pushes the branch, and a tag follows once the matrix is green.
On a function-oci branch the matrix also runs the OCI engine’s VM suite
(make oci.test) on nine pairs: the three most recent Firecracker minors against the three guest kernel
lines Firecracker supports (6.18, 6.1 and 5.10). The Dockerfile’s pins are the
current Firecracker and kernel, and the workflow’s env pins the others. The pair the image pins
alone blocks a release, and any other pair that fails stays
out of the record. A last job writes what the released function passed to a
tested-versions artifact: the function, the Crossplane versions and, for
function-oci, the pairs. The release skills use it to open the pull request
that updates the function’s table in README.md.
Security policy
This policy is for anyone who depends on function-wasm or function-oci or wants to report a vulnerability in either: how to report one, which releases receive fixes and where the fixes for each kind of code in this repository come from.
Reporting a vulnerability
Report a vulnerability through GitHub’s private reporting form, “Report a vulnerability” under the repository’s Security tab, rather than in a public issue. The report is private to you and the maintainers until the advisory is published.
Supported releases
Through 0.x the latest release line alone receives fixes; upgrade to the latest release to get one. From 1.0.0 on, an older release line can be patched on request.
The runtime
Each function’s function binary, its image, the workspace Cargo.lock
both binaries are built from, and the Crossplane package that embeds the
image: the code that runs in your cluster. function-oci’s image also
contains a guest init built from the same workspace, the Firecracker binary
from Firecracker’s release archive and the guest kernel that Firecracker’s
CI builds. The maintainers fix a vulnerability here as a patch release of
the latest release line. Every pull request runs cargo deny over the dependency graph of the workspace (deny.toml, with every feature on), so a
published advisory against a pinned crate fails the merge, and the same
check runs every week against main. Renovate opens a pull request when an
advisory affects one of the workspace’s crates.
The grype-scan.yml workflow scans each function’s latest release image
every week and reports what it finds to GitHub code scanning. function-oci
has no release yet, and its scan starts with the first one. Grype reads
package metadata, which in these images is the Chainguard base’s alone:
the C library, the GCC runtime libraries and the CA certificates. It
doesn’t see the crates inside the Rust binaries, which cargo deny checks
instead, and it reports nothing for Firecracker or the guest kernel.
crates/function-oci/Dockerfile pins both by checksum. Renovate opens a
pull request for each Firecracker release, and the maintainers move the
kernel by hand in that pull request, to the kernel the release’s CI built.
No scan in this repository alerts on a CVE in either.
Scaffolded projects
The projects guestfn init writes, from the templates under
crates/guestfn/templates/. You build and publish these. Each release
refreshes their dependency pins, so a project scaffolded with the latest
guestfn starts current. Once written, the project is yours: guestfn
doesn’t update it, so update its dependencies as you would in any other
project.
Examples
The guests under examples/ illustrate the guest languages. Four of them,
function-wasm-rust, function-wasm-ts, function-wasm-go and
function-oci-go (an image with its manifest layer), are published signed
under ghcr.io/jonasz-lasut/guestfn/examples/ (wasm-rust, wasm-ts,
wasm-go, oci-go), so a Composition can
reference them. The runtime images contain no example code, and both
packages embed the example manifests of examples/function-wasm-go/example and nothing else.
Renovate refreshes the examples’ dependencies in a monthly batch that merges
once the end-to-end suite passes, and its vulnerability pull requests against
them merge when their checks pass. The maintainers dismiss an alert against
an example when a sandboxed WebAssembly guest can’t reach the code or no fix
exists.
Use-case examples
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.11 (the artifacts published under the earlier names retired with the first publish under the new ones; the Zig and C scaffolds retired, #264; the examples named
function-<runtime>-<lang>and thefunction-oci-goexample, #263; the examples publish on their own, by hand, apart from the release, #245) - Tracking: https://github.com/jonasz-lasut/guestfn/issues/112
Context
A platform team deciding whether to put a WebAssembly module into a Composition needs to see a real use case, and a hello function in every language doesn’t show one. This record says which use cases the examples solve, why those, how the project tests the examples and how it publishes them.
What function-wasm adds
Existing functions already cover each use case below on its own:
function-cel-filter does conditional resources, function-tag-manager does
tags, function-status-transformer and function-auto-ready do status and
readiness, and Crossplane core is moving towards per-step, digest-pinned
function references chosen by the Composition author
(crossplane#7840). What
remains distinct to function-wasm:
- The composite resource can choose the logic.
module.fromreads the module source from an XR field, fenced by thecompositionPolicy’spullModule, andmodule.allowEmptymakes a step an empty hook until the XR fills it in. function-pythonic is the one other function with per-XR code, and it runs that code withexec(). - Untrusted code runs sandboxed by default. A module starts with neither network nor files nor environment. The manifest requests each capability, and both Cedar layers must permit it. function-python, function-shell and function-kcl run user code with the pod’s network and environment.
- Network access is requested, granted and audited. A module sends its request to the host, which resolves, checks the address against its block list, applies budgets and writes an audit line per request.
- One runtime, any number of modules. No install step per module: modules are pinned by digest and can be signature-checked.
An example belongs here when its use case needs at least one of these.
Selection
- Real demand, cited from crossplane/crossplane and crossplane-contrib issues (reactions at the time of writing) or a common infrastructure-as-code pattern.
- A different function-wasm feature per example, so the five together cover what the runtime offers.
- Renders from files alone: no cloud account and no internet. Egress examples fetch from a local fixture server.
- Crossplane v2 shapes: namespaced XRDs (
apiextensions.crossplane.io/v2) and namespaced provider resources (*.aws.m.upbound.io), with no claims. - The languages platform engineers use get the strongest stories, TypeScript and Python over C#.
Names
An example’s directory is function-<runtime>-<lang>: function-wasm-go,
function-wasm-rust, function-oci-go. The reader who comes for a language
finds it by name, and the use case stays in the example’s README and its
manifest’s description (Jonasz, 2026-11-08,
#263). The
manifest’s name follows the directory, and the published repository is
ghcr.io/jonasz-lasut/guestfn/examples/<runtime>-<lang>, the directory’s
name less its function- prefix (Jonasz, 2026-11-08): wasm-rust,
oci-go. The first publish under the new names was on 2026-11-09. The
artifacts published under the earlier names, at
ghcr.io/jonasz-lasut/wasmfn/examples/<name>, retired with it (Jonasz,
2026-11-09): the e2e profiles pin wasm-go and oci-go, and the registry
drops the old packages.
The examples
| Example | Language | Use case | What it shows | Demand |
|---|---|---|---|---|
function-wasm-rust | Rust (async, wasi:http 0.3) | Cloudflare alone may connect to an origin: a security group plus one ingress rule per range Cloudflare publishes, read at reconcile time | Egress through the host under both policy layers, the block list, conditional resources | crossplane#2712 (conditional resources); Terraform’s data "http" over Cloudflare’s lists |
function-wasm-ts | TypeScript | The organisation’s policy as the last step: mandatory tags, allowed regions and instance classes per environment | requirements through the wire-level proxy, fatal versus warning results | crossplane#1225, discussion #2617, provider-upjet-aws#169 |
function-wasm-go | Go (function-sdk-go) | A tenant add-on hook: a WebApp Composition’s last step runs the module the XR names; this add-on derives a PodDisruptionBudget from the desired Deployment | module.from, allowEmpty, the pullModule fence, the default sandbox | function-go-templating#24, crossplane#6139 (staggered rollout), crossplane#2524 |
function-wasm-python | Python | Team metadata from a CMDB, looked up with that team’s own token from one shared Secret keyed by the XR’s namespace | Step credentials, egress with an Authorization header, the composition layer fencing where tokens may go | crossplane#2099, crossplane#7343, provider-upjet-aws#169 |
function-wasm-csharp | C# | Dashboards as code: a sha256-pinned zip of Grafana dashboards unpacked into one sidecar-labelled ConfigMap per dashboard | The private /tmp, egress, integrity pinning, refusing archive entries that escape | Grafana’s dashboard sidecar, delivered as a versioned bundle |
function-wasm-cpp | C++ (mbedTLS) | A TLS Secret’s self-signed certificate kept fresh: read through the response’s requirements, reissued with a fresh P-256 key once fewer than renewBeforeDays remain | The read fence and the output fence scoped together, requires.resources and composes in the manifest, a C adapter over the generated structs | Self-signed certificates for internal services, rotated without cert-manager |
Design choices to keep:
- A failed external read is a fatal result, never an empty answer.
Crossplane applies nothing from a fatal pipeline, so
function-wasm-rust’s rules from the last reconcile stay in place while the module can’t read Cloudflare’s list (an empty answer would have deleted them). - Tenancy comes from the namespace, never from the
spec.function-wasm-pythonkeys the shared Secret by the XR’s namespace, which cluster RBAC sets. Keying by aspecfield would let an XR in the namespace of team A spend the token of team B. - A module sees the credentials its manifest names and no others.
function-wasm-pythondeclaresrequires.credentials: [cmdb], and the runtime forwards that credential where both policy layers permitspendCredentialand nowhere else; the pull credential and every other step credential, which the runtime edits out of the request before the run (#122). The tokens’ boundary is then egress, which the same two layers fence.
Unpublished hello examples
function-wasm-zig, function-wasm-c, function-wasm-odin and function-wasm-moonbit are the same greeting
guest in four more languages, each an ABI v2 component and none with a
scaffold. The Zig and C templates retired on 2026-11-08
(#264). Each of the four
examples has its plumbing in its own tree. The vendored proto and WIT are
checked in, and its gen-proto and gen-bindings targets write the codec and
the bindings. guestfn build
detects the first three by their build.zig and the MoonBit one by its
moon.mod (#155). Rust,
Python, TypeScript and Go are covered by the use-case examples in the table.
C# has function-wasm-csharp alone, C++ function-wasm-cpp alone. The language matrix is in
other languages.
The OCI example
function-oci-go is the hello function as an oci@0.1 module
(#263, phase 6
of the OCI runtime record). An ordinary
function-sdk-go function sits behind the SDK’s server. Its
Dockerfile cross-compiles it into an empty image, and guestfn push --image appends the manifest. It doesn’t share plumbing with a scaffold,
because the contract needs none. The build-oci-go job vets and
tests it and builds the image. Once it’s published, the oci e2e profile gets the case the
wasm lifecycle profile has with the published Go example: the module
pulled from ghcr.io with its real signature.
Testing
- Scaffolds are minimal hello projects. The guest suite
(
crates/function/tests/guests.rs) builds every language’s scaffold from its golden, which is whatguestfn initwrites, and runs the same ABI-level expectations over each: greetings, egress granted and refused, a guest-side fatal, logs. A scaffold has no lockfile. The suite resolves dependencies the way a user’s first build does, which caught the Go 1.27 break in #117. - Examples share the plumbing and nothing else with their scaffold - the vendored ABI
glue, the generated codecs, the proto and the WIT - which
examples_share_the_scaffold_plumbingholds byte-identical for the four pairs, Go, Rust, TypeScript and Python. The function, its manifest and its example manifests are the example’s own. An example with no scaffold has the plumbing in its own tree, and the drift check of its build job compares the generated code with the pinned generators. - Each example has unit tests in its language, covering each fatal path.
- Each example has a
build-<lang>job in the end-to-end workflow (e2e-wasm.yml, selected by thee2e:wasm:exampleslabel) covering its toolchain, the build, test and lint targets, and a drift check of its generated codec and bindings. - Nothing in CI asserts what an example composes. The Kubernetes-native
end-to-end suite (
crates/e2e, testing, #185) drives a committed test module of its own through Crossplane in a kind cluster. It covers the runtime behaviour the examples rely on (signatures,module.from, egress, credentials, env, the private/tmp, requirements, fatals, limits), and an example’s unit tests cover its own logic. make renderis the development loop of each example.examples/render.shrunsfunction validateover everyexample/xr*.yaml, then serves the directory withexample/policy.cedaras the operator policy andexample/fixtures/on a local HTTP server forcrossplane render(render locally).
Publishing
publish-examples.yml, run by hand, publishes the examples that work as
published as CNCF Wasm OCI artifacts, with their module manifests:
- Names:
ghcr.io/jonasz-lasut/guestfn/examples/<runtime>-<lang>, beside the WIT world atguestfn/function. A namespace per kind of artifact is the convention across OCI-distributed WebAssembly plugins (Kubewarden’spolicies/, wasmCloud’scomponents/). - Versions: each example’s semver comes from its
guestfn.yamland is taggedv<version>, independent of the runtime’s. A version already published is never pushed again (the same registry probe aspublish-wit). Each run publishes the examples whose version moved and skips the rest, and a published tag remains immutable. - When: a maintainer runs the workflow from
mainafter the version of an example moved. The examples have a lifecycle of their own. A release neither builds nor carries them, and a failed example build stays out of the package’s publish run. - Signing: keyless cosign plus SLSA provenance from the publish workflow,
with no key in the repository. The runtime verifies the keyless signature
against a Sigstore trusted root (
--cosign-trusted-root) and admits it where the operator’strustSignerrule names this repository’s release workflow on a version tag (#116; the signatures page has the rule); an operator may still countersign with its own key instead. - References: the registry’s:
repo:v<version>for people, the digestguestfn inspectprints for a Composition’smodule.oci.ref. The workflow commits nothing back and attaches nothing to a release. - An OCI module:
function-oci-go’s image is built bydocker buildxforlinux/amd64andlinux/arm64and pushed into the same repository by digest, under no tag.guestfn push --imagethen publishes the module, the image with its manifest layer, asv<version>, the repository’s one tag per version (Jonasz, 2026-11-09), and the signature covers that digest.oci-go0.1.0 predates this and also hasv0.1.0-image. - Which:
function-wasm-rust,function-wasm-ts,function-wasm-goandfunction-oci-go.function-wasm-pythonandfunction-wasm-csharprequest egress to placeholder hosts (cmdb.example.org,artifacts.example.com) that their users replace before publishing their own.
Alternatives
A health rollup (crossplane#5643) lost because an XR’s Ready already
aggregates its composed resources’ readiness, and Crossplane drops a function’s
Healthy condition (with Ready, Synced, UpToDate and Responsive).
A subnet layout from a VPC CIDR lost because upbound/function-cidr already
covers it and it doesn’t show a feature the table lacks.
Operations (Operation, CronOperation, WatchOperation) lost because the
package declares the composition capability alone, and module.from has no
composite resource to read in an Operation.
An AssemblyScript example and a TinyGo scaffold with hello-tinygo were
retired on 2026-10-07 (#114).
AssemblyScript has no component-model path, and #114’s spike showed that
hand-written canonical-ABI glue covers run and log but makes wasi:http a
hand-maintained cost. TinyGo builds the world on its own wasip2 target, but
its bindings generator is unmaintained and the Go flavour can’t share it. The
go scaffold and function-wasm-go instead build a wasip1 reactor that guestfn build embeds the world into and wraps.
The Zig and C scaffolds retired on 2026-11-08
(#264). A guestfn init
template exists for a language with an official function-sdk-<lang> under the
crossplane GitHub organisation (Go, Rust, TypeScript and Python), the
languages a function author expects a project to support. Zig and C have none, and the
project maintained two template sets, their goldens and two guest-suite cases
for a scaffold nobody asked for. function-wasm-zig and function-wasm-c stay
as examples, checked by their build jobs, like Odin, MoonBit, C# and C++, and
guestfn build still builds a build.zig project.
Open questions
The world’s publication (#106):
the examples target guestfn:function@1.0.0, frozen on 2026-10-07
(#77). The
Publish WIT workflow (publish-wit.yml) publishes it, run by hand from a
wit-v<version> tag.
Design records
The design records live under docs/ as one-pagers, one per feature, each
headed by its owner, reviewers and status (draft, implemented with a
revision, withdrawn or superseded). Each describes the design in today’s Rust workspace,
the alternatives it rejected and the questions still open. The
status below is each document’s own. make vale checks this table and
the book’s contents against the status line of every record. A revised
record fails the prose job until both say the same.
| design record | status |
|---|---|
| ABI v2 and the Rust host | Implemented, revision 0.10 |
| Compiled-artifact cache key | Implemented, revision 1.0 |
| Module and compiled artifacts cache | Implemented, revision 2.9 |
| Module configuration from the composite resource | Implemented, revision 1.1 |
| Module manifest | Implemented, revision 1.8 |
| Module source schema | Implemented, revision 2.5 |
| OCI runtime | Draft |
| Per-image microVM snapshots | Draft |
| Read fence | Implemented, revision 1.0 |
| Runtime resource governance | Implemented, revision 1.8 |
| Three-layer authorization model | Implemented, revision 1.5 |
| Trust model | Implemented, revision 1.13 |
| Use-case examples | Implemented, revision 1.11 |
| WASM sandbox | Implemented, revision 1.10 |
The guest ABI isn’t a one-pager: ABI v2 is the contract itself, with its own version.
ABI v2 and the Rust host
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 0.10 (revision 0.10 serves the SDK’s
generated service, where the gRPC layer was a raw-codec transport. Rewritten in the present tense over the
Rust workspace. The Rust host has served since v0.3.0, the world froze on
2026-10-07, took the name
guestfn:function@1.0.0and a sync form on 2026-11-10, and ABI v1 was removed in 1.0.0;Publish WITpublishes the world from awit-v<version>tag, #106, and guests pull it and WASI at build, pinned by digest inguestfn.lock)
function-wasm runs guests as WebAssembly components against one WIT world, and its host is written in Rust. This record explains why those are one decision, what ABI v2 is at design level, what the move left alone, and how the risks turned out. The contract itself, the world and its rules, is the ABI v2 reference.
Why Rust and v2 are one decision
ABI v2 means running components, and the component gap was in the Go binding,
not in the engine. wasmtime-go could load a component but couldn’t call one,
define host functions on the component linker or register WASI 0.2 and
wasi:http (#280),
and the draft PRs #290 to #292 were still open. The Rust wasmtime crate is the
reference component host: component::bindgen! over a WIT world, host
functions, wasmtime-wasi, wasmtime-wasi-http with an overridable
send_request and the WASI 0.3 async work. Committing to v2 meant either waiting on a volunteer binding effort or
leaving Go. A CGo shim for components was the middle road, and the other
road was moving the host to the engine’s own language. The project took the
latter (Jonasz, 2026-08-25).
The move brings these with it:
- Native
cedar-policy, Cedar’s reference engine. The hierarchy and pattern code the Go runtime wrote around cedar-go (the boundary-correctRepositoryhierarchy,dialAddresshandling) ported across and now sits incrates/function/src/authz.rs. - The Wasmtime API the Go binding never exposed: parse-without-run inspection, a
pre-linked
InstancePreper module so a run does nothing but instantiate, and the engine’s pooled memory budget, which suit a fresh instance per request. guestfnfollows the runtime, since it links the engine for its verdicts, so one move covered both.
What ABI v2 is
A guest is a component targeting the WIT world guestfn:function@1.0.0:
- It exports
run: async func(list<u8>) -> result<list<u8>, string>. ProtobufRunFunctionRequestbytes go in andRunFunctionResponsebytes come out, the same wire format ABI v1 used. The world isn’t a typed WIT mirror of the messages. WIT has no recursive types, so it can’t expressStructorValue, and payload evolution stays Protobuf’s job. The canonical ABI moves the memory, so a guest has no allocator export. - It imports a typed
log, and WASI 0.3 and 0.2 under the sandbox. Egress iswasi:http, 0.3client.sendand 0.2outgoing-handleralike, which the host bridges onto one grant held to the egress policy. Guests use their language’s own HTTP client, and whether the import is backed by the egress client follows fromrequires.egress.httpunder the three layers. - The binary format is the version: a component is ABI v2, and the runtime refuses a core module at load.
The world targets WASI 0.3 from the start (Jonasz, 2026-08-25), accepting
young toolchains for the first guests. wasi:http@0.2 and @0.3 are different
interfaces, so defining the world against 0.2 and lifting it later would
have meant cutting two worlds and designing the streams and budgets twice.
Wasmtime enabled component-model async by default in v46, so the host had
nothing to wait for. A run lifted sync satisfies the async world,
which is what the WAT test fixtures use and what the package’s
function-sync world states for the toolchains that need it. Wasmtime calls its 0.3 support experimental, so a release that
moves those interfaces moves the WASI versions guests import (abi-v2.md,
“Versioning”).
Async matters less here than for most hosts. A fresh instance per request
doesn’t need concurrent calls into one instance, which leaves the benefit in
the wasi:http import. Its bodies are native streams, and the egress
budgets count bytes as the host forwards them.
What didn’t change
Everything host-language-neutral moved over verbatim: the Input schema and
manifest format, the Cedar semantics of both policy layers, digest-pinned
sources, the three cache stores, the refusal strings, the flags, /readyz
and gRPC health, and the metrics series. AGENTS.md (“Parity with the Go
runtime”) lists the recorded divergences. The ABI is host-agnostic: the five example guests passed the
ported behavioural suite unchanged.
The port was built against a differential harness that diffed
function validate output and exit codes against the Go binary over shared
fixtures and live servers and registries. When the Go tree was removed, the
recorded outputs became the conformance goldens, so a behaviour change is a
deliberate re-record.
Risks and how they turned out
- Bandwidth. The port was months of feature-frozen solo work while the Go host kept getting fixes. The conformance suites bounded what done meant, and the Rust host replaced the Go one in v0.3.0.
- Security-sensitive ports: the egress dialer judgment, redirect re-checks and the repository hierarchy. Their tests ported with them, and the fixtures diff the refusal strings.
- function-sdk-rust maturity: the runtime became its first hard consumer.
The runtime assembles its own gRPC server
(
crates/function/src/grpc.rs) over the SDK’s generated service, with the SDK supplying the messages and helpers. The server used a raw codec until function-sdk-rust 0.6.0 kept unknown fields on every message. - Registry and signing clients. The registry client is hand-written over
reqwest(crates/function/src/oci.rs) rather than a published OCI crate. Signature checking moved to cosign 3 bundles oversigstore-verify, so the Go runtime’s cosign 2.sigformat isn’t read, the one divergence beyond wording. wasi:httpbudgets. Budgets that counted whole responses count bytes on the stream (crates/engine-wasm/src/wasihttp.rs).- Specification and toolchain youth. Churn did land. ABI v1 was removed
rather than served indefinitely, because Go reached v2 through
guestfn build’s embed and wrap (#114). Therustscaffold pinned a beta toolchain until Rust 1.100.0 madewasm32-wasip3a stable target. - The static musl binary on a
FROM scratchimage, once expected from dropping CGo, didn’t happen: the image stays on the Chainguardglibc-dynamicbase.
Non-goals
- A typed WIT mirror of the RunFunction messages.
- A second world for WASI 0.2 alone. A toolchain that reaches 0.2 alone would need a second world defined, tested and kept consistent with the first.
- Changing a guest-facing semantic during the port.
Alternatives
- A Go host with a CGo component shim, or waiting on wasmtime-go’s binding PRs. Both put the project’s critical path in someone else’s work, and the shim would have to track Wasmtime’s component API by hand.
- wazero. A probe showed the guest ABI is host-agnostic, which is what made the host swap safe, but wazero doesn’t run components, so it couldn’t carry v2.
- ABI v1 kept alongside v2, served indefinitely. The first plan, because mainline Go had no WASI beyond wasip1. The spike for #114 moved Go onto v2 by embedding the world into a wasip1 reactor and wrapping it with an adapter, so no scaffold needed v1 and 1.0.0 removed it.
- componentize-go for Go guests. It proved the approach, but
guestfn builddoes the same embed and wrap with the runtime’s own adapter, so users don’t install anything extra. - A
run-jsonexport besiderun, for guests that would rather skip a Protobuf codec. Decided against (Jonasz, 2026-08-26): the TypeScript guest came together on protobuf-es and the Python guest on the Protobuf package’s pure-Python fallback, and a second export would double what conformance covers. - A sibling repository for the Rust host. The workspace lived beside the Go modules in this repo while the port ran against their fixtures; the Go tree was then removed.
Compiled-artifact cache key
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.0 (a key drawn per process and no flag, for finding F-2 of the 1.0 security audit)
The compiled tier of the cache, /tmp/guestfn-cache/compiled/<version>/,
contains Wasmtime artifacts: native code the runtime maps and runs through
Engine::deserialize_file, whose soundness rests on the file being the
runtime’s own output. The fetched-module and manifest stores verify what
they read against the digest in the file’s name. The compiled store can’t do
that, because an artifact’s name is the digest of the module the runtime
compiled it from, which says nothing about the artifact’s own bytes. Anyone
with write access to the directory could plant an artifact under a
legitimate digest, and the runtime would run it once the module’s own checks
had passed. The store now refuses every artifact it didn’t write itself.
Design
The runtime draws 32 random bytes at startup (getrandom) and keys the
compiled store with them (store.rs, Store::with_key). It keeps the key
in memory and writes it nowhere, logs it nowhere and shares it with nothing.
putwrites the artifact, then an HMAC-SHA256 of its bytes under the key as<name>.macbeside it, each through a temporary file and a rename. A crash between the two leaves an entry with no sidecar, and the next lookup refuses it.pathreads the entry and its sidecar, recomputes the MAC and compares it in constant time before it hands the path to the engine. A missing or wrong sidecar isLookup::Stale: the store removes both files and the cache countscache_events_total{cache="compiled-disk",event="stale"}. The module compiles again, writing a new entry under its own key.- The sweep and the
cache_bytesgauge skip sidecars, and the sweep removes a sidecar with its entry.
A restart draws a new key. The previous process’s artifacts on a persisted volume fail the check once, and the runtime compiles the modules again. The volume still spares the pod the fetch: the modules store serves the bytes, verified against their digest. Pods must not share a volume, since each would refuse and overwrite the other’s artifacts. Each pod gets its own.
Decision
Jonasz (2026-10-28) chose a key drawn at startup over a key mounted from a
Secret behind a flag. A flag means one more thing for every operator to
configure, and he accepted the price of the per-process key: a cold compile
of every module after a restart, with or without a persisted volume. The
audit’s draft of this record proposed the opt-in --cache-key-file.
Alternatives
Storing the module’s digest inside the artifact, or beside it, binds nothing: whoever can plant an artifact can plant the digest with it. A secret the writer of a planted file doesn’t hold alone distinguishes the runtime’s output from anyone else’s.
A key mounted from a Secret (--cache-key-file) would keep a persisted
volume’s artifacts valid across a restart. It also means one more flag and
one more Secret for every operator, and a key outside the process is a key
someone can read. Rejected (Jonasz, 2026-10-28).
Signing the artifacts with the operator’s cosign key would tie the cache to the signature path and cost a public-key verification per load. The MAC is symmetric and local. No party in the trust model needs to verify the runtime’s own artifacts except the runtime.
Trade-offs
A MAC over the whole artifact is one pass over the file per cold load from
disk, proportional to the artifact’s size (tens of megabytes for a large Go
module). The runtime pays it once per process per module, since the memory
tier keeps the mapped module from then on. The sidecar doubles the number of
files in the compiled store. The compile after a restart is the accepted
price. --warm-modules moves it ahead of readiness.
Tests
store.rs checks that a keyed store serves what it wrote and refuses an
entry under another key, a planted entry and a tampered one, removing what
it refuses. cache.rs makes the audit’s reproduction permanent. The cache
refuses an artifact planted under a digest and fetches and compiles the
module, and a second cache under the same key serves the entry the compile
wrote. The lifecycle end-to-end profile, whose cache is a PVC, checks that a
restart reuses the fetched module and refuses the previous process’s
artifact.
Contract impact
An operator configures nothing, and the refusal wording and the goldens are the same as before. The cache section of the trust model, the cache storage section of the flags page, and the sizing and readiness pages describe the per-process key and what a volume keeps.
Module and compiled artifacts cache
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 2.9 (revision 2.9 answers
RunFunctionwithUNAVAILABLEuntil warm-up ends, where a request that arrived during warm-up was served cold. Revision 2.8 has the sweep skip the root filesystem of an image function-oci has in memory. Revision 2.7 keys the compiled tier per process, the cache key record’s design. Revision 2.6 puts the manifests tier to use, perf-02 of the performance audit under the F-5 rule. Revision 2.5 states the cache posture of the 1.0 audit’s F-5, and 2.4 the compiled tier’s trust boundary. Revision 2.3 rewrote the record in the present tense over the Rust workspace, where warm-up loads its entries one after another and skips the signature check, which every request makes before it reads a cache)
function-wasm keeps its caches on disk under one fixed directory, every entry
addressed by a content digest, plus a bounded in-memory tier for compiled
modules. The runtime checks each tier before it serves it. It verifies the
fetched modules and the manifests against their digest. It verifies the
compiled artifacts, native code Wasmtime loads without a check of its own,
against an HMAC under a key the process draws at startup
(the cache key record), and compiles a module again
when another process wrote its artifact. Fetched modules are always written to disk and never held in memory.
Compiled modules are persisted as Wasmtime artifacts, mapped from disk when
needed and held in memory while they’re used. An entry never has to be
invalidated: its name is its content. The flags are safety limits (the number of
modules that stay resident, the number that compile at once), not cache tuning, and
--warm-modules decides when the runtime fills the caches (before readiness),
not how.
Layout
/tmp/guestfn-cache/
├── modules/ fetched blobs, as delivered by the source
│ └── sha256-<hex> verified against its name on every read
├── compiled/ Wasmtime artifacts
│ └── <engine::version()>/ e.g. rust-v<wasmtime version>-linux-aarch64
│ ├── sha256-<hex> the artifact for the module that digest pins
│ └── sha256-<hex>.mac its HMAC under this process's key; an entry
│ with no sidecar or another key's is refused
├── manifests/ module manifests by their own digest (the manifest
│ └── sha256-<hex> layer's for an OCI source, manifestDigest for an HTTP
│ one), verified against the name on every read
└── tuf/<instance>/ with --cosign-trust-instance: the verified TUF
metadata and trusted root of that Sigstore instance,
outside the LRU sweep (which walks the stores above)
The directory is DEFAULT_DIR in crates/function/src/store.rs, created at
startup. A pod that must keep its caches across restarts backs it with a
volume (a DeploymentRuntimeConfig with an emptyDir survives container
restarts, a PVC lasts across rescheduling). With a root filesystem the container can’t write to, the
pod must mount something writable there. A directory that can’t be created
stops the runtime at startup, naming it: running without caches would re-pull
and recompile on every restart, unnoticed.
Store writes each entry through a temporary file and a rename. A crash
can’t leave a partial entry for a later read to serve. The modules/
store is opened verifying: a read recomputes the digest, and a mismatch removes
the entry and counts as a miss. The compiled store can’t verify by name,
since an artifact’s name is its module’s digest, so it verifies by key.
put writes an HMAC-SHA256 sidecar beside each entry under 32 bytes the
process draws at startup, and path checks it before it hands the path out.
A missing or wrong sidecar is a stale miss that removes the entry. The
runtime keeps the key in memory and nowhere else. A restart compiles every
module again, a volume keeps the fetched modules and the manifests and nothing else, and
the store refuses a planted artifact.
Keys
Every key is a sha256:<hex> stated in the Input (or computed for a served
file, module.path, hashed when its size or mtime change), so resolving never
touches the network and no reference is resolved at request time:
- An OCI source is keyed by the manifest digest in its reference
(
repo[:tag]@sha256:..., printed byguestfn push; a tag alone isn’t accepted). The manifest pins the module by stating its layer’s digest. The registry client verifies the manifest against the reference and the layer against the manifest. The compiled artifact is keyed by the manifest digest;modules/keeps the layer under its own digest, as delivered. A raw WASM layer’s digest is the module’s. A tar layer is stored as a tar and extracted when the module is compiled, so every blob is verifiable against its name. - An HTTP source is keyed by
module.http.digest, the digest of the module bytes. The runtime verifies the download against it before storing or compiling it.
A cache entry is then the content its name promises, byte for byte, and a module
fetched from two sources shares its blob when the bytes are the same. The
key is also everything a hit checks. A module one Composition pulled with a
registry credential is served without a fetch to any later request that
states its digest, whatever the source type. The runtime checks the
credential at the pull and never at a hit, and a digest quoted in a
Composition is no secret. The module’s manifest is kept per digest per
process the same way, and the signature verdict per repository and digest,
since the operator policy decides whose signature counts per repository.
The resolver remembers a
manifest by the digest that pins it, and a warm request doesn’t contact the
registry. The raw bytes also go to the manifests/ store under their own
digest, verified on read like every disk tier but the compiled one. A
process that lost the memory tier reads the artifact’s manifest once per
digest, with the credential, to learn the layer’s digest, and takes the
layer from disk. A guestfn.yaml under --module-dir is never cached: it’s
the development loop.
The compiled store is namespaced by engine::version()
(crates/engine-wasm/src/wasm.rs): the Wasmtime crate version build.rs reads
from Cargo.lock, plus the OS and architecture. A serialized artifact loads
in no Wasmtime but the one that produced it, on the same host type, and a bump moves the namespace on its own. The rust-v
prefix keeps the namespace apart from any directory an earlier runtime left on
a volume. At startup remove_stale_versions deletes the
other version directories under compiled/ once nothing has written them for
STALE_VERSION_AGE (a day). The running binary can’t load them, but during a
rolling upgrade pods of both versions share the volume, and deleting each
other’s artifacts on start would recompile everything twice, while a rollback
within a day finds its cache warm. Loading is defensive anyway: an artifact
that Wasmtime refuses counts as stale and is recompiled over.
Tiers and the request path
RunFunction (crates/function/src/runner.rs)
└─ resolver.resolve(module) no I/O: digest from the Input (or file stat)
└─ verifier cosign, when required - before any tier
└─ cache.get(digest, fetch) crates/function/src/cache.rs
│
├─ memory hit → run (idle TTL 10 min, refreshed on every use;
│ LRU beyond --max-cached-modules)
├─ compiled/<version>/<digest> hit → map the file (no copy) → memory → run
└─ miss → one load per digest, shared by every waiter
fetch: (resolver.rs)
oci: manifest GET (verified against the ref) → layer digest
├─ modules/<blob digest> hit → bytes (blob hit)
└─ miss → source (registry layer / HTTP GET / file) (blob miss)
→ verify sha256 → modules/<blob digest> ← write
oci tar layer: extract /fn.wasm
→ wait for a compile slot (--max-concurrent-compiles, default 1)
→ compile → serialize → compiled/<version>/<digest> ← write
→ memory → run
- Memory (compiled modules). One entry per module in use, dropped after
DEFAULT_IDLE_TTL(10 minutes) of idleness or, with--max-cached-modules, when it’s the longest-unused entry past the bound. A request after that goes to the artifact on disk, not back to the network or the compiler. Loads are single-flight per digest: concurrent first requests for one module wait for one load. A failed load isn’t remembered, and the next request retries. At most--max-concurrent-compiles(default 1) modules compile at once. A compile uses every core and about a gigabyte for a large guest, and more in flight multiplies that. A cold load isn’t cut short by the request’s deadline: the compile completes and caches, and the run that follows gets the remaining budget.--enable-memory-cache=falseturns the tier off: every request maps the artifact from disk and releases it. - Compiled artifacts on disk. Written after every compile, mapped on every
memory miss with
Engine::deserialize_file, and the code is file-backed and shared with the page cache instead of copied onto the heap. Restarts and rolling upgrades cost that map instead of a compile; a Wasmtime upgrade costs one compile per module and, a day later, drops the old directory. - Fetched modules on disk. Written after every successful fetch, read before
any download. With it, an HTTP server outage doesn’t stop reconciling for
modules seen before, and a rescheduled pod with a volume never re-pulls. An
OCI module whose artifact is gone costs one manifest read (kilobytes, to
learn the layer digest) and no download. Served files (
module.path) aren’t copied: they’re on disk already.guestfn pushandoras pushproduce rawapplication/wasmlayers, which cost nothing to extract; a compressed tar layer is decompressed on every artifact miss.
The runtime holds raw module bytes in memory during the compile call and at no other time. Warm-up is the same path entered at startup instead of at a request.
Warm-up
Ready isn’t warm by default: the first request for each module on a pod pays a
map (warm volume) or a compile (cold). --warm-modules (repeatable, one
comma-separated value, or WARM_MODULES) names modules to load first: OCI
references pinned to their manifest digest (pulled with the runtime’s Docker
config, since there is no step credential at startup) and, with
--module-dir, path:<file> entries. warm in crates/function/src/ops.rs
resolves each entry and calls the same cache.get a request does, so a warmed
module is what a request would have loaded, whichever tier supplies it. It doesn’t check signatures. That stays the
request’s job, made before any cache is read, so a warmed module that isn’t
signed is never served where a signature is required. The order:
- The caches open. A failure here refuses to start.
- The gRPC and health servers start listening, both reporting not serving.
A probe reads not-ready rather than a refused connection, and a request that
arrives before warm-up ends is answered
UNAVAILABLE(the function is not ready), as function-sdk-rust’s own server answers one (Jonasz, 2026-11-19). Its caller retries. Before that decision such a request was served cold. - With
--cosign-trust-instance, the first trusted-root fetch runs, bounded and logged on failure, because a warmed module may need it. - The entries load one after another.
/readyzand gRPC health flip to serving.
A failure is logged (Cannot warm module, with the entry and the reason, such as a
tag instead of a digest or an unreachable registry) and nothing else. Readiness is never held back by an entry, and
the module it names loads on its first request as before. Warm-up costs time
between listen and serving, one map per entry on a warm volume and one compile
per entry on a cold cache, so a gRPC liveness probe on the function port needs
a failure threshold that outlasts it. A volume under
/tmp/guestfn-cache is what makes that time short. The operator’s view
is readiness.
Failure behavior
- Disk write failure at run time (full volume, transient I/O error): ignored by the caller. The request proceeds with the fetched or compiled result, and the next miss tries again.
- Corrupt blob (digest mismatch on read): removed, treated as a miss.
- Corrupt or foreign artifact (Wasmtime refuses it): treated as a miss and counted
stale. The recompile overwrites it. - The signature check happens before any tier is consulted, once per repository and manifest digest per process, so an artifact that a keyless runtime left on a shared or persisted volume is never served by a runtime that requires a key.
- A digest stated in the Input (or by the manifest it pins) that differs from what the source delivers is a fatal result stating both digests, and nothing is stored.
Observability
guestfn_module_cache_events_total{cache,event} with cache in
compiled (memory tier), compiled-disk (artifacts) and blob (fetched
modules), and event in hit, miss and stale (compiled-disk alone: an
artifact Wasmtime refused). guestfn_module_fetch_duration_seconds{source}
and guestfn_module_compile_duration_seconds time the miss paths.
guestfn_module_cache_bytes{cache} is the size of the blob and
compiled-disk stores as of the last sweep. The metrics page lists the full
series: metrics.
Eviction
Disk entries aren’t evicted by default: they’re immutable and named by digest,
and a Composition that stops referencing a module leaves its files behind.
--max-cache-size (in MB) turns the sweep on. At startup and every ten minutes
it removes the longest-unused entries across the three stores (a read
counts as a use: the store touches what it serves) until nine tenths of the
bound is left, so consecutive sweeps don’t each remove one entry. A removal is
always safe, since every entry is reproducible; the next request fetches or
compiles again. A mapped artifact whose file is swept keeps serving the
resident module, because the open mapping doesn’t depend on the file’s name.
function-oci has one exception. A run’s VM opens the image’s root
filesystem by its path, and an image in memory whose file went would fail
its runs until it left memory. The engine pins the stored root filesystem
of a loaded image in the store, and the sweep skips a pinned entry. The
entry still counts toward the total. While the images in memory alone
exceed the bound, the stores stay over it. The image leaves memory by the
idle TTL or --max-cached-modules, and from then on the sweep takes the
file like any other.
Alternatives
Eviction on by default. Entries are reproducible and cheap to keep, and a default bound would be a number the project can’t choose for every volume. The sweep is opt-in.
Flags for the disk tiers. Every option for them was a way to run without a
cache, so the design has one directory and one idle TTL. The flags that remain
(--enable-memory-cache, --max-cached-modules, --max-concurrent-compiles)
bound memory and CPU and leave both disk caches on.
Warm-up from a list of every module ever served. What to warm is the operator’s list, each entry a digest (never a tag) stated the way a Composition states a module. A pod doesn’t resolve anything at startup either.
Module manifest
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.8 (
abiiscontract,<engine>@<major>.<minor>, anoci@0.1manifest nestsimageandargsunderoci, andminRuntimeis gone, for the OCI runtime record; the manifest file isguestfn.yamland its layer’s media type is undervnd.guestfn, #241; therequires.resourcesdeclaration besidecomposes; rewritten in the present tense over the Rust workspace; merges in the manifest-less-sources record, revision 0.1, whose manifests by reference are a section here)
A module declares what it needs in a manifest: the sandbox capabilities it
can’t run without and the schema of the config it reads, plus, as advice alone, the kinds it
composes. For an OCI artifact
the manifest is a second layer of the artifact. A Path or HTTP source
names its guestfn.yaml by reference. The runtime reads it before the run and fails
fast, with a message that identifies the module and the refusing policy layer,
when a requires entry isn’t permitted or the config doesn’t match the
module’s schema. Registries and guestfn inspect show what a module needs
before anyone runs it, and guestfn scaffold composition writes the Input
from it.
A manifest never widens anything. It’s the request of the
three-layer decision, granted where the
Input’s compositionPolicy and the operator’s --sandbox-policy-file both
permit, and nowhere else. The manual page is Module manifests.
Principles
- A manifest is a request, never a grant. Its effects stop at an earlier, clearer refusal, documentation and scaffolding. The composition and operator policy layers still grant, and either can refuse.
- Beside the module, inside the artifact. The manifest is a layer of the same OCI artifact as the module, so the manifest digest a Composition pins names it and a cosign signature of that digest covers it. The module bytes are untouched, and nothing parses WebAssembly to find it (Wasmtime alone decodes a module).
- Absent is fine. A module without a manifest gets the default sandbox.
Unknown top-level fields are ignored in a published manifest, and an
unknown entry under
requiresfails closed. - Language-agnostic.
guestfnwrites it from a file next to the project, independent of any SDK or toolchain feature, so every guest language is equal.
Shape
The source is guestfn.yaml in the project (every scaffold includes one):
contract: wasm@1.0 # required; the world of docs/abi-v2.md (oci@0.1: the gRPC contract)
name: greeter # → org.opencontainers.image.title
version: 0.1.0 # → …image.version; guestfn push --module-version overrides
source: https://github.com/example/greeter # → …image.source (optional)
requires: # what the run must be granted; each optional
egress:
http: # the same rule shape as the Input's egress rules
- host: api.example.com
methods: [GET]
pathPrefix: /v1/
filesystem: {privateTmp: true}
env: # secret env: bindings to step-credential keys
- name: DATABASE_URL
fromCredential: {name: db, key: url}
credentials: [cmdb] # step credentials read whole from the request
config:
schema: # JSON Schema 2020-12, inline; validates the Input's config
type: object
properties: {greeting: {type: string}, greetingUrl: {type: string, format: uri}}
additionalProperties: false
composes: # advisory: what the module writes
- kind: policy/PodDisruptionBudget
changes: [add]
The layer. guestfn push adds the manifest as UTF-8 JSON in a layer of
media type application/vnd.guestfn.manifest.v1+json after the
application/wasm layer and lists both digests in the artifact config’s
layerDigests. It also sets the standard org.opencontainers.image.*
annotations (title, version, source, description, revision) from the
manifest and --revision, for registry UIs. The runtime never reads them. A
manifest is at most 64 KiB. requires.egress.http takes the same rules as the
Input’s egress rules, so a request and a compiled grant compare like with
like. requires.env binds variable names to step-credential keys and
requires.credentials names the step credentials the module reads whole from
its request. The values arrive at the pipeline step, never in the manifest,
and the request the module receives contains the credentials these two
name and no others: the runtime edits every other one out of it. oras push fn.wasm:application/wasm guestfn.json:application/vnd.guestfn.manifest.v1+json produces the same
artifact.
Who writes it. guestfn build reads guestfn.yaml when present and
validates it, so a project with a bad manifest doesn’t build. The parse is
strict and refuses unknown fields, and the egress rules and env bindings pass
the runtime’s own checks. guestfn push reads it again and
adds the layer. The manifest is a data file, not something declared in the
guest’s code: anything in code would need instantiating the module to read,
and the manifest must be readable without running the module. A guest’s own glue never writes it.
Decided by the policy layers. In the request path, after admission and the
load and before the run, admission::admit_requires decides every requires
entry by the three-layer rule. Each egress rule (once per rule and method, so
a policy can key on context.method), filesystem.privateTmp, each env
binding (setEnv over the bound names, spendCredential per binding) and
each required credential (spendCredential) must be permitted by the Input’s
compositionPolicy (scoped default-permit: it narrows the actions it
writes rules for and no others) and by the operator’s --sandbox-policy-file
(default-deny). Then Manifest::check holds the rest of the manifest against
the run:
contractis one the engine offers (a development build, which has none, passes);- the Input’s
config(absent is{}) validates againstconfig.schema.
A miss is a fatal result, counted as refused, before the module runs:
module oci ghcr.io/example/greeter@sha256:3f2a… requires egress GET to host "api.example.com" (requires.egress.http[0]), which the operator policy (--sandbox-policy-file) does not permit
… which the compositionPolicy does not permit
… requires a private /tmp (requires.filesystem.privateTmp), which the operator policy (--sandbox-policy-file) does not permit for this request
… config does not match the module's schema: /greeting: got number, want string
The runtime checks the composition layer first, whole: the author closest to the fix reads their own layer’s refusal even where the operator would also deny. A manifest can make a run fail earlier. It can’t make a run possible.
Declared output. composes lists the <group>/<Kind> a module writes and
the changes it makes (add, modify, remove, all three when omitted). It’s
advisory (#174). The runtime never reads it and judges the module’s actual
output against the policy layers’ composeResource rules, since a
refusal before the run would be unsound for rules conditioned on a resource’s
name. The tooling reads it: function validate --resolve warns where a
declared change would be refused, guestfn inspect shows it and guestfn scaffold composition writes the matching permits.
Declared resources work the same way: requires.resources lists the
<group>/<Kind> a module asks Crossplane for through its response’s
requirements and how it selects them (by: name, labels, both when
omitted). Of the requires entries, this one alone the runtime never grants
or refuses before the run. It’s advisory (#208), judged after the run over
the actual selectors against the policy layers’ requireResource rules, and
the same three tools read it, where function validate --resolve judges a
declared read with an empty name or no labels and no namespace.
guestfn scaffold composition prints a Composition step, or with --full
a Composition, whose module is a Path for a file or the pinned OCI
reference, whose config is a skeleton from the schema (required keys with
placeholders, defaults where the schema has them) and whose limits are
commented. The module’s sandbox needs are its manifest’s requires, granted
by the policy layers and never copied into the Input. guestfn push prints
the requires: block under the module: block it prints, which shows a
Composition author what the policy layers must permit.
Manifests by reference
A Path source (a .wasm file under --module-dir) or an HTTP source (a
file fetched by URL and digest) has no artifact to hold a layer, and an OCI
artifact pushed without a manifest layer has none either. With no manifest the
request is empty, so by the model’s default-deny the module gets the
default sandbox and nothing more. That’s safe, but it leaves an operator who legitimately runs a
Path or HTTP module that needs egress, a private /tmp or a
credential-sourced env var with no way to request it (tracked in
#30).
A manifest is a request, nothing more. A manifest-less source misses nothing but a
place to put its guestfn.yaml: the document the module author already writes
and guestfn push embeds, stored beside the module instead of inside the
artifact. Such a source names it by reference:
module:
type: HTTP
http:
url: https://example.com/fn.wasm
digest: sha256:...
manifestURL: https://example.com/fn-manifest.yaml # optional
manifestDigest: sha256:... # pins it
---
module:
type: Path
path: fn.wasm
manifestPath: fn-manifest.yaml # optional, under --module-dir
- The referenced file is a
guestfn.yaml. The resolver normalizes it to the JSON an OCI manifest layer contains, soManifest::parseis the one decoder. It verifiesmanifestURLagainstmanifestDigest, bounds the file to the manifest size limit and readsmanifestPathunder--module-dirwith the same confinement as the module file. - It arrives through the same
Resolver::manifestcall as an OCI manifest layer, soadmit_requires,Manifest::checkandfunction validate --resolveare unchanged. A referenced manifest meets the same three layers as an embedded one, and it can refuse a run earlier, never make one possible. A file the runtime can’t read or parse is a fatal result,cannot read the manifest of module <desc>: …ormodule <desc> has an invalid manifest: …. - Caching follows the manifest’s own identity, not the module’s: the same
module file may run with one manifest, another, or none. An
HTTPmanifest is content-addressed bymanifestDigestand kept in the blob store. AmanifestPathmanifest is read fresh on every request and never cached, so the local loop (--module-dirandcrossplane render) reflects an edit at once. manifestPathis allowed with no type butPath. An OCI artifact takes no reference: its manifest is a layer.
The from fence
When the composite resource chooses an HTTP source (module.from), a
compositionPolicy pullModule rule must permit the manifest’s normalized
location, as it must the module URL; otherwise the XR author could point the
runtime at any host to GET. The refusal is module.from: <field> of the composite resource names manifestURL "<location>", which the compositionPolicy does not permit (pullModule). A manifestPath has no host, so the fence
doesn’t apply to it, and it comes from the Input alone: module.from can’t set
it, since an XR author chooses the module file, not what its manifest
requests.
Mechanics
crates/function/src/manifest.rsholds theManifesttypes.loadreads theguestfn.yamlof a project and refuses unknown fields,parsedecodes a layer (at most 64 KiB, unknown top-level fields ignored, an unknownrequiresfield refused),validatechecks the egress rules, env bindings and credentials through the same functions the Input’s use and the schema compiled as JSON Schema 2020-12 with thejsonschemacrate.checkholds the manifest against the run’sGrants, andsummaryis the line the CLIs print.crates/function/src/resolver.rs:Resolver::manifestreturns the manifest as JSON bytes, empty when the source has none. The OCI case reads the artifact’s manifest, picks the manifest layer and fetches it through the blob store, verified against the layer’s digest and bounded to the size limit. The other two cases are in the preceding section.crates/function/src/runner.rsreads and parses the manifest between the load and the run, then callsadmit_requiresandManifest::checkin that order.function validate --resolve(validate.rs) reads the same manifest, prints its summary on the resolved line and applies the same decision with the same refusal.crates/guestfn:buildvalidatesguestfn.yaml;push [--manifest f] [--module-version v] [--revision r]adds the layer and annotations;inspect <ref>andmanifest show <ref>read the layer;manifest validate [guestfn.yaml]checks the file;scaffold compositionwrites a step or a Composition. The flag is--module-versionbecause the root--versionis taken by the CLI’s own.
Trust and threat notes
The manifest is a request both policy layers must permit, so it can refuse a
run or document a need. It never grants or widens, and it never affects
another module’s run (there is no “denies” list). In an artifact it travels
under the manifest digest the Composition pins: whoever can change it can
change the module, and --cosign-key covers both. A manifest by reference is
pinned where it can be: an HTTP manifest by manifestDigest. config.schema
runs a validator over Composition-authored data, and a manifest, and so its
schema, is bounded to 64 KiB. Reading the manifest parses JSON, never
WebAssembly. Failing closed on unknown requires.* means a module asking for a
capability this runtime doesn’t know is refused with a message, not run
without it. These checks never read the composite resource.
Decisions
- An OCI layer, not a custom section (Jonasz, 2026-08-17). The manifest
is a second layer of the artifact, so the same digest and signature cover
it, no parser is needed, and
oras pushcan produce it. The cost accepted:PathandHTTPsources have no layer, so they name theirguestfn.yamlby reference, and aguestfn manifest setthat embeds into an existing module has no meaning and doesn’t exist. - Environment variables are a
requiresentry (Jonasz, 2026-08-19, which reversed 2026-08-17). The first design left environment values to the Composition. The three-layer change removed the Input’s env fields, so the manifest is where a module declares its env contract:requires.envbinds a variable to a step-credential key, whichsetEnvandspendCredentialmust permit in both Cedar layers. requiresis hard. An unmet entry refuses the run. Anoptional: trueper rule can be added later without breaking anything.config.schemais enforced by the runtime, not byguestfnalone. A guest already fails on a bad config, but later and with a worse message, while the runtime’s refusal identifies the field.- The module author is the one request author for every source kind. A manifest by reference keeps one author and one schema for what a module needs, at the cost of a second small file to publish or place.
- The home of the manifest is the artifact or the referenced file.
guestfn pushderives the OCI annotations from it for registry UIs and the runtime never reads them. - The source file is
guestfn.yaml.
Alternatives
- Manifest-less means the default sandbox and nothing else. The simplest option, and
it nudges everyone to OCI and
guestfn push. Rejected as the answer by itself: it breaks the local loop for any module that needs egress, and a module hosted over HTTP has no path to a capability at all. - An inline
requestblock in the Input, valid for manifest-less sources alone. The Composition would author the request for these sources alone, so a module would have two possible request authors and two schemas to keep aligned. - A sidecar
guestfn.yamldiscovered beside aPathmodule. Rejected for an explicitmanifestPath: a source states what it loads and nothing is picked up implicitly, with one field pattern (manifestURL,manifestPath) covering both kinds. - The manifest as a
wasmfn.manifestcustom section of the module. Reading it needed a walker over WebAssembly sections beside Wasmtime, which the admission-tooling design had ruled out (a second reader of a module). - Environment variables listed under
requiresas keys the module reads. Dropped in the first design, when environment values were the Composition’s, and superseded by the env bindings in the decisions.
Non-goals
- Letting a referenced manifest grant anything. It’s a request; the two Cedar layers decide. A permissive manifest on a runtime with no operator policy still gets the default sandbox.
- An inline
requestin the Input. If a use case appears for a Composition-authored request on a manifest-less source, it can be added later over the sameRequiresschema. - A reference and an embedded manifest on the same OCI artifact.
manifestURLandmanifestPathare for the sources with no layer.
Module source schema
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 2.5 (revision 2.5 reads the registry of an OCI reference into one canonical form; the Input’s group is
guestfn.crossplane.io, the generic name both runtimes serve, with the CRD generated frominput.rs, #242; rewritten in the present tense over the Rust workspace)
The Input is what a Composition step hands the runtime. A discriminated
module says what runs, and the fields the Composition author controls sit
beside it at the top level. The 2026-08-16 architecture review
raised it. The user-facing field reference is
the Input reference; this record keeps why the
Input is structured this way and what compositionPolicy and limits decide. The
trust model describes what the compositionPolicy
fence means, resource governance
limits, and the sandbox the capabilities a manifest
may request.
The Input, in one place
apiVersion: guestfn.crossplane.io/v1
kind: Input
module: # what runs - required
type: OCI # OCI | HTTP | Path - always the Composition's choice
oci: # exactly one of the typed object …
ref: ghcr.io/example/greeter:v1@sha256:…
credentials: registry
# http: {url, digest, manifestURL?, manifestDigest?} # a manifest-less source may name its guestfn.yaml
# path: fn.wasm # with, optionally, manifestPath: fn-manifest.yaml (under --module-dir)
# from: status.module # … or the XR field holding it (an object of `type`)
# allowEmpty: true # with from: an unset field runs nothing (desired state unchanged)
compositionPolicy: | # the composition author's Cedar layer (three-layer-authz one-pager)
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example-org");
limits: # what this step's run may consume, ≤ the runtime's ceilings
timeout: 5s
memory: 128Mi
config: # opaque, forwarded to the module
greeting: hi
module is required; compositionPolicy, limits and config are
optional. A document of the group of 0.6 and earlier,
wasm.fn.crossplane.io in either of its versions, is refused by name
(input::renamed_group, see Compatibility).
Everything but module (and within it, the object from names) is read from
the Input alone, never through module.from: an XR author may choose the
module but may not widen its permissions, grants or budget. The Input has no
sandbox subtree. A module requests anything beyond the default sandbox in
its manifest’s requires. The runtime grants a capability when the
manifest, the compositionPolicy and the operator’s --sandbox-policy-file
all permit it, and not otherwise (three-layer authorization).
function validate refuses an Input with the removed policy
or sandbox field and names the replacement (the Input's policy field was removed: …, the Input's sandbox field was removed: …).
Why this structure
A source is chosen in one of two places: the Composition author writes it
into the Input, or an XR author names it in a field of the composite resource.
Rules that depend on where a source came from (an XR-chosen source may reference a
credential where the Composition permits it and inside an allowed
registry, never elsewhere) belong in the structure of the schema. A type discriminator
next to a typed object is the Crossplane idiom, and from is an orthogonal
switch on it:
module.typesays what kind of source the step runs. The Composition author always chooses the kind, an XR author the instance alone.- One, and no more, of the typed object (
oci,http,path) orfromis set, and no object of another type may be present. The runtime checks it on every request. Three CEL rules on themoduleobject say the same for tooling that reads the schema (crossplane resource validate, IDEs), such asself.type == 'OCI' ? (has(self.oci) != has(self.from)) : !has(self.oci)and its two siblings. Crossplane never installs a function’s Input CRD (an Input is a fragment of a Composition), so the runtime is the one gate that always runs:admission::admitandfrom::from_compositeapply every rule the CRD underpackage/wasm/input/states. - The Composition-owned rules are top-level siblings of
module, never read from the XR. The CRD’s CEL requires a non-emptycompositionPolicywhenmodule.fromnames an OCI or HTTP source. limitsis the other top-level sibling.- An object read through
frommay reference a credential where thecompositionPolicypermitsspendCredentialand for a ref apullModulepermit admits, never otherwise. The XR can’t bypass that rule, because the policy never comes from the XR.
module.from and allowEmpty
module.from names a field of the observed composite resource under spec.
or status. (pattern-checked), read on every request. from_composite
decodes it, refusing unknown fields, into the object type names (an
{ref, credentials} object for OCI, {url, digest} for HTTP, a string
for Path) and then validates it like a static source. An error quotes the
field: module.from: status.module of the composite resource is not a {ref, credentials} object: …. A field the composite resource hasn’t set is
an error naming it (module.from: cannot read status.module from the composite resource: module: no such field).
module.allowEmpty: true changes that case. The step doesn’t run a module and
returns the request’s desired state and context unchanged, built at the wire
level from the caller’s own bytes and counted as
requests_total{outcome="skipped"}. A field that’s set is read, fenced and
run as without it. allowEmpty is read from the Input alone and
refused without from: the Composition author chooses whether a step may be
left empty, the composite resource whether that step is (issue #82). It
serves the reserved hook of the first use case (use cases)
before any tenant fills it in, and a smoke test of a deployed runtime that
doesn’t need a module built.
compositionPolicy and what an XR-chosen module may be and spend
Refusing credentials on XR-chosen modules would be safe but blunt: a platform
team that wants tenants to pick modules from the platform’s private registry
would have to mount a Docker config into the runtime. compositionPolicy
fences what an XR-chosen module may be and spend instead:
module:
type: OCI
from: status.module # the XR names {ref, credentials}
compositionPolicy: |
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example-org");
permit (principal, action == Action::"spendCredential", resource == Credential::"registry")
when { context.repository in Repository::"ghcr.io/example-org" };
It’s raw Cedar over the same schema as the operator’s policy, compiled at
admission (content-hash cached). Malformed Cedar is a fatal result. For an
XR-chosen source it’s a required, default-deny fence. The XR’s oci.ref (or
http.url), normalized, must be permitted by a pullModule rule over the
Repository hierarchy. A named credential also needs a spendCredential
permit, whose context.repository contains the ref’s location so both halves
co-locate. For sandbox actions it narrows and does nothing else, and it
narrows where it scopes the action. A static source skips the fence: the Composition named it and is
trusted with it. The XR keeps choosing the artifact; the Composition keeps
choosing where from and with what. The same field serves signature-free
deployments that still need to fence tenants to a registry.
The Repository hierarchy is boundary-correct: Repository::"ghcr.io/example-org"
admits ghcr.io/example-org/mod but never the sibling namespace
ghcr.io/example-org-other/…. A trailing slash is optional and doesn’t
change the boundary.
The runtime reads the registry part of an OCI reference into one canonical
form before the entities, the signature check, the registry client or a
message see it. The host is lowercase, a trailing dot and the default port
are dropped, and Docker Hub is index.docker.io. A registry part that isn’t
a host name or an IP address with an optional port is refused at admission.
A policy whose Repository has another spelling is refused when it’s
compiled, since its rule would match no module
(the canonical registry).
A manifest-less source can reference its manifest instead: module.http.manifestURL
together with manifestDigest, or module.manifestPath with type: Path
(module manifests). The runtime loads it as it
loads an OCI manifest layer, so the three-layer decision is identical. For a module.from http source the manifestURL is fenced by
pullModule like the module URL. The Input alone supplies manifestPath.
limits and per-composition budgets
The ceilings are global (--module-timeout, --module-memory-limit), so a
trusted internal module and a tenant’s labelling module would get the same
budget. The operator sets the ceiling and the Composition requests less, so
the Input has a top-level limits, read from the Input alone (an XR author
must not widen a budget). admission::admit checks each value against its
flag at request time. Asking for more is a fatal result that quotes both
(limits.memory 1Gi exceeds the runtime's --module-memory-limit of 512Mi);
asking for less narrows that run’s epoch deadline and memory limiter in the
engine’s RunOptions. Raising a limit past the ceiling remains the operator’s call.
A Composition author who sets limits with little headroom gets fatal results
the operator didn’t cause. The benefit is a shared runtime where the loudest
module can’t spend the whole ceiling.
Alternatives
Optional fields under module (oci, http, path and a *From
pointer for each) with a CEL rule that one, and no more, is set would work. It
presents every source kind twice. Each new kind adds two fields, and the
policy fields would still have no home.
source: {kind, oci, http, path} nested one level down is the chosen
structure with an extra level and gains nothing.
Putting from inside the typed object (oci: {from: status.module}) reads
well for one kind, but path: {from: …} turns a string into an object, and
the credentials rule then needs an “if from is set” check inside each object.
policy and limits under module would tie Composition-owned policy to the
thing an XR may choose. As top-level siblings they’re visibly not part of
what from reads.
Dropping from sources altogether removes the whole class of XR-author
decisions, but loses the per-tenant case that the use cases lead
with.
Module configuration from the composite resource
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.1 (revision 1.1 makes the
configedit on function-sdk-rust’s message, where 1.0 made it on the request’s raw bytes; phases 2 to 4, #262; the open questions settled: objects alone,guestfn scaffold xrdlater)
The Input’s config block is today a value the Composition author writes
and the runtime forwards to the module verbatim, checked against the module
manifest’s config.schema. That design answers one question, how the author
configures a module they picked, and it stops making sense the moment the
module is code the Composition didn’t pick. With module.from the composite
resource chooses the module, the author can’t know its schema, guestfn scaffold composition has no skeleton to write, and the schema check doesn’t
check anything. The tenant who chose the code has no sanctioned way to
configure it, short of a module reading its own fields out of the composite
resource, which the runtime neither checks nor documents. This record
replaces the value with a reference: config becomes an object that says
where in the composite resource the module’s configuration is, and the
runtime reads it, checks it against the schema of the chosen module and hands the
module the result. Static configuration goes. The record targets the
WebAssembly runtime on main; the OCI runtime (the OCI
runtime record, its code in
#251) adopts it
once that code has merged and its contract has settled. Jonasz decided to drop the
static value on 2026-11-07.
Who knows what about a configuration
A module’s configuration has two authors with different knowledge. The
module’s author knows its structure and writes it down as config.schema
in the manifest. The person who deploys an instance of the module knows the
values. In a Composition pipeline that person is whoever writes the
composite resource, since the composite resource is the one object per
instance. The Composition author sits between the two and assembles the
pipeline; they know the module’s structure as its author alone and the values as the
instance’s owner alone. A value
written in the Composition exists once per Composition, the tenant it
serves can’t change it, and in the module.from case the author wrote it
against a schema they haven’t seen.
Kubernetes already has the two places this information belongs. A
structure goes in the OpenAPI schema of the composite resource definition, which
the API server enforces at admission, and defaults go there too, where the
API server applies them. The module manifest’s config.schema is a JSON
Schema and transplants into that definition unchanged. What the Composition
then has to say is one thing: which field of the composite resource the
module reads. The runtime still checks the value against the manifest’s
schema, as the backstop, since a definition without the schema is valid,
and because the fatal result it writes states the module and the path.
Static configuration had one remaining use, settings the author fixes for every instance. Those are the definition’s defaults, or the module’s own. No code in the project composes a static value with a per-instance one, and a merge rule between the two would be a third place to look for a setting.
The field
apiVersion: guestfn.crossplane.io/v1
kind: Input
module:
type: OCI
from: spec.addOn
compositionPolicy: |
permit(principal, action == Action::"pullModule", resource in Repository::"ghcr.io/example-org/webapp-addons");
config:
from: spec.addOnConfig # the composite resource field with the module's configuration
# allowEmpty: true # an unset field runs the module unconfigured
config is an object with two fields, both read from the Input alone:
config.from(required withinconfig): a field of the observed composite resource underspec.orstatus., with the same grammar and the same reader asmodule.from. The field contains the module’s configuration as the module’sconfig.schemadescribes it, an object in every scaffold.config.allowEmpty(optional, default false): with it, a field the composite resource leaves unset (absent or null) runs the module unconfigured, the state a module is in today when the Input has noconfig. Without it an unset field is a fatal result that states the field. The default is strict, asmodule.from’s is: the Composition author declared where the module’s configuration comes from, and silence is a mistake until the author says it isn’t.
An Input without config runs the module unconfigured, as today. The
runtime refuses any other key under config by name, so a 0.6-style value
fails at admission with a sentence that says where the value now belongs.
The object, rather than a string path beside module, is what leaves room
for the next field. allowEmpty is the first. A future field has the same
home.
The runtime’s steps
from::from_composite does the reading at admission, in the same step and
under the same rules as for module.from, from the observed composite
resource of the request and before the resolver sees the module. A request
without an observed composite resource, a path the resource doesn’t have,
or a value that isn’t an object is a fatal result worded as module.from’s,
with config.from in place of module.from:
config.from: cannot read spec.addOnConfig from the composite resource: addOnConfig: no such field
config.from: spec.addOnConfig of the composite resource is not an object
config.from spec.addOnConfig: no observed composite resource to read it from
Once the runtime has read the module’s manifest (step 6 of runner.rs),
it checks the value against config.schema the way it checked the
static value, and the refusal keeps its wording, module <desc> config does not match the module's schema: /greeting: got number, want string. A
module without a schema accepts any object. An unset field under
allowEmpty skips the check, as an absent config does today.
The module receives the configuration where every guest already reads it:
input.config of its request. The forwarded request is the caller’s with
the edits the runtime may make (runner.rs), and this is one more. Before
it forwards the request, the runtime replaces the config entry of the
Input’s Struct, where the caller wrote {from: …}, with the resolved
value. The Input is the one field of the request whose schema is the
runtime’s own, and since google.protobuf.Struct is a map, the edit
keeps every key the caller wrote, known or not. The rest of the request,
the observed composite resource included, passes with every field it had.
Under allowEmpty with an unset field, the
runtime removes the config entry, so GetConfig reports an unconfigured
module rather than a from reference.
The guest glue doesn’t change. GetConfig reads input.config, as it
does on every scaffold today, and a module built before this record runs
unchanged. The world doesn’t change either, and the contract remains
wasm@1.0, since nothing in the host-guest ABI moved; the group
guestfn.crossplane.io/v1 takes the new config object before any release
includes it.
Security
Configuration widens nothing. Capabilities come from the three policy
layers and the manifest, credentials from the step’s credentials and the
manifest’s requires.env bindings, never from config, and the Cedar
schema doesn’t mention it. A tenant who sets spec.addOnConfig controls
what a module they could already choose (under module.from) or what the
Composition author exposed of a fixed module, within the schema the
module’s author published. The runtime checks the value against that
schema, so a module’s author can rely on the structure they declared. The
API server’s bound on the composite resource bounds the value’s size.
Secrets don’t belong in configuration. The guests’ page repeats this for
tenant-authored configuration, and points at step credentials.
compositionPolicy and limits remain read from the Input alone, as required by
the record titled Module source schema.
config joins module.from as the second thing the composite resource may
author.
Checks offline
function validate applies the rules of config to every step and, with
--xr, reads config.from from that composite resource and prints the
runtime’s own refusal where the read fails. With --resolve it checks the
value against the resolved module’s schema, as it does today for the
static value. The conformance goldens record every refusal:
config.frommissing fromconfig, or the path outsidespec./status.- an unknown key under
config, stating the key and the two that exist config.allowEmptywithoutconfig.from(the object makes this a structural error rather than a semantic one, but the sentence remains for a reader who wrote the field alone)- the three read failures of the preceding section, and the schema refusal
The CLI
guestfn scaffold composition writes config: {from: spec.config} in the
step and, from the manifest’s config.schema, a commented definition
fragment beside it: the spec.config property with the schema
transplanted, ready to paste into the composite resource definition. A new
guestfn scaffold xrd writes a whole definition skeleton for a module,
with the same property and x-kubernetes-preserve-unknown-fields: true
where the manifest has no schema. The scaffolds’ example/composition.yaml
move their greeting to the example composite resource and reference it, so
a freshly scaffolded project renders the way the record says.
Compatibility
config changes from an opaque value to an object of from and
allowEmpty. The group guestfn.crossplane.io/v1 has no release behind
it yet, and the runtime refuses the 0.6 group wasm.fn.crossplane.io by
name, so no served API changes meaning. The
Compatibility page lists the new field and
its rules among the 1.x promise. The runtime refuses a static value with a
sentence that states config.from and never forwards it, so a Composition
written against a pre-release build fails at admission and says what to
write.
Phases
- This record.
- The runtime:
input.rs(Config { from, allow_empty }, the CRD regenerated),from.rsreads the field,admission::admitapplies the rules,runner.rsreplaces the Input’sconfigentry and shares the steps withvalidate.rs, fixtures undertestdata/validate/and conformance goldens for every sentence, the Input reference, the guests’ page and troubleshooting updated. guestfn scaffold composition‘s step and fragment,guestfn scaffold xrd, the six scaffolds’ examples and goldens, the guest suite’s configured-greeting cases moved to the observed composite resource.- The use-case examples (
function-wasm-python‘scmdbUrl, the hello guests’ greeting) moved to their composite resources and definitions. - The OCI runtime, after its code merges: the same
configobject, delivered through the same edit in the request the runtime passes to its gRPC server.
Alternatives
- Keep the static value beside
config.from, merged. Fixed settings for every instance beside per-instance ones, with the Composition’s keys taking precedence. Rejected. The definition’s defaults, which the API server applies, are those fixed settings, and a merge rule would add a third place a setting can come from. - A
configFromstring besideconfig. Additive, so a module whose configuration has afromkey would keep working. Rejected once the value goes: nothing collides with the key any more, and the object leaves room forallowEmptyand the next field. - Configuration inside the
module.fromobject.spec.addOn: {ref: …, config: {…}}, the choice and the settings together. Rejected: thefromobjects are the source types, which decode without extra keys. A fixed module with tenant-tunable settings has nomodule.fromto put them in. - Resolution in the guest glue.
GetConfigfollows the reference itself. Rejected: nine glues and every hand-written guest would have to agree, and the runtime couldn’t check what it never read. - Default-lenient,
config.errorOnEmpty: trueto make an unset field fatal. The same switch the other way. Rejected for symmetry withmodule.allowEmpty: one word and one default across the two fields the composite resource may author.
Open questions
Both settled by the owner on 2026-11-08 (Jonasz, #262):
config.fromreferences an object. The scaffolds all declare objects. The runtime refuses a scalar or a list withconfig.from: <field> of the composite resource is not an object, and the question returns with a module whose schema declares otherwise.guestfn scaffold xrdfollows later. The commented definition fragmentscaffold compositionwrites covers the common case.
OCI runtime
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: draft (a second runtime that runs OCI images in a microVM behind the same manifest and policy layers as a WebAssembly module. The owner settled the packaging and the contract and the egress and the artifact and the names and the order on 2026-11-05. The renames and the Engine trait and the manifest’s type merged on 2026-11-06 (#244, #246, #247). The first
function-ocibuild runs a process under Firecracker behind theSandboxseam. On 2026-11-09 the owner kept Firecracker for now and left scaffolding and building an image to its author, withguestfn pushto publish it. The engines and the two functions became crates of their own the same day. Snapshots are in 0.1 as an alpha feature. The egress proxy gets a design of its own first, in #280, and #281 has the order to 0.1) - Tracking: https://github.com/jonasz-lasut/guestfn/issues/239
Summary
function-wasm runs one kind of module, a WebAssembly component, in one
kind of sandbox, Wasmtime. The code around the sandbox doesn’t depend on
it. The Input and its module sources, the module manifest, the policy
layers, the credential withholding, the egress client, the fences, the
caches, the signature check, function validate and the guestfn loop of
init, build, push and inspect all work on bytes and references. The
engine alone knows what a module is.
This record adds a second runtime, function-oci, built from the same
workspace. It runs an OCI image, any image, as the step’s module, inside a
microVM with its own guest kernel. The runtime boots one VM per request
from the image’s root filesystem. The VM has no network device. The
image’s command starts the FunctionRunnerService gRPC server every
Crossplane function is, and the runtime calls it over vsock. A small init program the runtime boots as the VM’s
first process provides the services the WebAssembly guest gets through its
world. The manifest’s contract states the engine, wasm@1.0 or oci@0.1,
and the artifact guestfn push publishes moves to generic media types. Both
runtimes then share the manifest format, the artifact layout and the CLI.
The operator installs the runtime they need. The WebAssembly package
remains small and unprivileged. The OCI package needs /dev/kvm on its
nodes.
The project is at 0.6 and the owner accepts breaking changes before 1.0.
The names tied to WebAssembly that the OCI runtime would inherit change
outright, with no alias: the manifest file becomes guestfn.yaml, the
artifact’s media types move under vnd.guestfn, and both packages serve
the Input as guestfn.crossplane.io/v1. Firecracker is the sandbox for
now (Jonasz, 2026-11-09). The status stays draft until the first
function-oci package, which makes it implemented, revision 1.0.
Goals
- An OCI image as a module. Composition steps reference an image, or
an artifact that wraps one, through the same
moduleblock. The runtime admits, fences, meters and audits it as it does a WebAssembly module. A reader ofdocs/how-a-request-runs.mdfinds the same nine steps, with step 8 running a VM instead of a component. - Hardware isolation by default. The image’s code runs under its own guest kernel under a hypervisor. The guest can attack the hypervisor’s surface, not the container runtime’s.
- Nothing beyond the sandbox’s grants. The VM has no network interface. The manifest requests egress, env bindings and credentials, and both policy layers permit them, as today. A guest that ignores the proxy the init offers has no route at all.
- One CLI.
guestfn push --imagepublishes an image as a module, with its manifest appended as one more layer.guestfn inspectshows what the runtime sees in it, andfunction validate --resolveadmits a Composition offline. - One manifest.
requires,composesandconfigkeep their meaning. A platform team’s Cedar policies and manifest reviews transfer without a second vocabulary.
Non-goals
- Running the image as a plain container. A container shares the host
kernel, and
function-oci0.1 runs on KVM alone (decision 9). - A second ABI for WebAssembly. The component world remains the one WebAssembly contract. The OCI contract is a gRPC server in the VM.
- Scaffolding and building the image. The author writes the project
and its
Dockerfileand builds the image with their own tools.guestfnpublishes the result (decision 12). - Renaming the WebAssembly package. The repository became
jonasz-lasut/guestfnat 0.6 (#252); the packages,function-wasmandfunction-oci, kept their names. - Kubernetes-level sandboxing. The runtime never creates Pods, Jobs or
RuntimeClass workloads. It remains a gRPC server, and
crossplane renderand the Development runtime keep working. - GPU, block devices, host mounts. The VM sees its root filesystem, a scratch overlay and the init. It sees nothing from the pod.
Design
Two packages, one workspace
crates/function becomes generic over an Engine trait. The trait is what
runner.rs already calls. compile produces the cached, loadable form of
a module from its bytes or its reference. inspect reports the module’s
layout and its contract verdict, for guestfn and validate --resolve.
run serves one request under RunOptions, with the egress requester, the
env, the private scratch and the deadline. version namespaces the
compiled store, and the engine registers its own metric series. The
Wasmtime engine in crates/engine-wasm keeps its behaviour behind the
trait. crates/engine-oci runs the microVM behind the same trait, through
a Sandbox trait of its own with Firecracker behind it. Each package has
a binary crate, crates/function-wasm and crates/function-oci, that
hands the runtime its engine and the engine’s flags:
| package | engine | image contents beyond the binary | the node needs |
|---|---|---|---|
function-wasm | Wasmtime | none | none |
function-oci | Firecracker | the Firecracker binary, the guest kernel, the init | /dev/kvm |
One binary never serves both. A function-oci pod that meets a type: wasm artifact refuses it with one sentence that states the other package,
and the other way round. A step pointed at the wrong package fails at
admission with that sentence. function validate validates for the
runtime it runs in and prints the same sentence.
The contract of the OCI package is young. Its documentation labels it alpha until the contract and the sandbox flags have stayed the same through two minors. The package has versions, tags and releases of its own (decision 15).
The contract
A module of contract oci@0.1 is an OCI image. The runtime runs the image’s
configured entrypoint and command once per request, as the image’s
configured user, in the image’s configured working directory, with the
image’s configured environment plus the bindings the manifest requested.
The command starts a FunctionRunnerService server on port 9443, and the
runtime calls RunFunction once that port accepts a connection:
| part | content |
|---|---|
| the request | the RunFunctionRequest the proxy forwards, as the component’s run receives it. The engine takes the message and sends it with function-sdk-rust’s generated client |
| the response | the RunFunctionResponse the client decodes. The proxy adds meta when the guest omitted it, as today. Bytes that don’t decode read as a status other than OK, Internal, in prost’s words |
| a status other than OK | module <desc> failed: run returned an error: <message> (gRPC status <code>), a fatal result on a fresh response, as a component’s err(string) is |
| standard output and standard error | log lines. A line that parses as a JSON object with level and msg becomes a typed log line with its other keys as fields. Every other line logs at info. module and digest attach as they do for the typed log import |
| the process ending before it answers | module <desc> failed: process exited with status <n> before answering the call: <the last log line> |
The process gets the image’s own arguments, or the manifest’s oci.args in
place of the image’s command: a function on a Crossplane SDK demands mTLS
without --insecure, and the call stays inside the VM. The runtime
sends it no signal before the deadline. At the deadline the runtime kills
the VM and returns the deadline fatal in the wording family the engine uses
today. The process sees /tmp writable and the rest of its root
filesystem writable through an overlay the VM discards on exit.
requires.filesystem.privateTmp remains accepted and keeps its meaning, a
scratch space private to the run. The manifest’s contract field states
this contract as oci@0.1 and the component world as wasm@1.0: the
engine kind, then the version of that engine’s contract. From a contract’s
1.0 a later minor extends it with new fields. The runtime reads the engine kind from
the field and refuses a version its engine doesn’t offer. The field
was abi, an integer, through 0.6. An OCI image has no ABI, so the owner
replaced it with no alias (decision 10).
The artifact
guestfn push publishes one artifact per WebAssembly module: the
application/wasm layer and the manifest as a second layer of media type
application/vnd.guestfn.manifest.v1+json, under a WASM config that lists
the layer digests and the standard org.opencontainers.image.*
annotations. guestfn push publishes an OCI module the same way, as the
image plus one layer. guestfn push <ref> --image <image@sha256:…>
appends a gzip tar layer holding the manifest at /.guestfn/manifest.json
to the image’s manifest. The layer’s diff_id and a history entry go into
the image config, and the annotation io.crossplane.guestfn: manifest
onto the layer’s descriptor, the way Crossplane’s xpkg append adds a
package’s extensions. The result goes into the image’s repository under
the reference given. An index gets the layer in each of its platform
manifests.
The appended layer is an ordinary filesystem layer. The image remains a
valid OCI image that every container runtime pulls and runs. The Input
pins the module’s digest, which covers the image and the manifest, so one
cosign signature covers both and the trust model doesn’t change. The
runtime finds the annotated layer in
the manifest and reads that one small blob before it pulls the rest, so
admission refuses before any layer comes down. An image with no such layer
runs as a manifest-less module in the default sandbox, as a bare
application/wasm layer does. function-wasm refuses a module image by
name, since the package for the OCI runtime serves it.
The generic media type application/vnd.guestfn.manifest.v1+json replaced
application/vnd.wasmfn.manifest.v1+json outright for WebAssembly
artifacts, and the runtime reads the old one no longer. A WebAssembly
artifact pushed by an older guestfn runs again after a push by the new
one.
The manifest
contract: oci@0.1 # the engine and its contract's version; wasm@1.0 is the component world
name: tagger
version: 0.3.0
oci:
image: ghcr.io/acme/tagger@sha256:… # written by guestfn push
args: ["--insecure"]
requires:
egress:
http:
- method: GET
host: cmdb.example.org
path: /teams/
credentials: [cmdb]
config:
schema: {…}
The other fields keep their meaning and their validation. guestfn manifest validate holds oci.image to a digest-pinned reference and refuses it in a
wasm@1.0 manifest. guestfn push --image <ref@sha256:…> writes the
image’s digest into the published manifest as the module’s provenance and
appends the manifest to that image, with no module file read. guestfn inspect says that a module image is one and which image the manifest
records as its origin, and --pull refuses it: the OCI runtime pulls and
boots the image.
The file is guestfn.yaml for both contracts. The
rename from wasmfn.yaml goes through the scaffolds, the examples, the
goldens, module.manifestPath‘s documentation and the guests’ pages in
one change, with no alias.
The sandbox
Firecracker is the sandbox for now (decision 8).
What boots. The runtime unpacks the image’s layers once per image
digest, applies the whiteouts and preserves ownership and modes without
root, into the form the sandbox boots from. For a VMM with nothing but block devices,
that form is a squashfs image, which the runtime writes
straight from the layer tarballs with its blocks packed with zstd
(the packing of the root filesystem, after this paragraph); a VMM
that shares files through virtio-fs takes a directory instead. The image config, with the user
resolved against the image’s /etc/passwd and /etc/group, goes
inside the squashfs, so a stored root filesystem describes itself. The
runtime keeps the unpacked files in memory until the squashfs exists, so it
bounds what an image unpacks to. The layers may unpack to eight times
--module-size-limit between them, the rule a WebAssembly module’s tar
layer follows. They may contain a million entries. The runtime
stops reading a layer where the image passes either bound and refuses the
image. A whiteout or an opaque marker removes what the layers below left,
whatever its place among its own layer’s entries. An entry under a symbolic
link to a directory goes where the link leads inside the root filesystem,
as a container runtime puts it. The runtime refuses a path with a ..
segment, an entry under a file, and an entry at the path of its own config.
It leaves device nodes out, because the guest’s /dev is the kernel’s
devtmpfs. The
content-addressed store keeps the result beside the compiled WebAssembly
artifacts, under engine::version(), under the same LRU sweep and the
same per-process key. The key check refuses a planted root filesystem
before the VMM sees it. The guest kernel comes with the package, either
built by the project from a microVM configuration or supplied by the VMM,
and Renovate tracks it with the VMM. The first build takes the kernel
Firecracker’s CI builds from Amazon Linux’s microVM kernel (6.18, the
guest kernel Firecracker supports since 1.16.1, with squashfs, overlayfs,
cgroups, virtio and vsock built in), pinned by checksum with Firecracker’s
release in crates/function-oci/Dockerfile and the Makefile. The artifacts
are at a dated prefix of Firecracker’s bucket, whose retention the project doesn’t
control. Building the kernel in the repository from that source and
config is what the record calls the project’s own kernel build. Whether a
release may include the published kernel is open
(#281).
guestfn_module_compile_duration_seconds measures the unpacking.
The packing of the root filesystem. The squashfs blocks are zstd at level 3. The guest decompresses every block the process reads, at the start of every run, so the packing is part of a run’s latency. A CI runner measured it on 2026-11-13, 30 runs per cell in one job, with the engine’s squashfs of each image written again with each of the other compressors:
| image | packing | squashfs | written in | a booted run, median | a restored run, median |
|---|---|---|---|---|---|
function-oci-go, 37.4 MiB | gzip | 12.20 MiB | 1450 ms | 552 ms | 448 ms |
| zstd 1 | 12.83 MiB | 137 ms | 434 ms | 333 ms | |
| zstd 3 | 12.22 MiB | 173 ms | 436 ms | 321 ms | |
| zstd 19 | 10.45 MiB | 13 263 ms | 444 ms | 329 ms | |
| stored | 37.39 MiB | 402 ms | 292 ms | ||
| the fixture, 9.2 MiB | gzip | 3.35 MiB | 338 ms | 321 ms | 186 ms |
| zstd 3 | 3.36 MiB | 42 ms | 294 ms | 170 ms |
Level 3 gives the size gzip gave. A run of the Go example reads it about
120 ms sooner, and the image’s first load writes it in an eighth of the
time.
A higher level buys disk alone: level 19 is 14 % smaller, takes 77 times
as long to write and runs no faster. Level 1 saves 36 ms of a first load
for 5 % more disk. A squashfs that compresses nothing runs another 30 ms
faster at three times the disk. The guest kernel has to read zstd
(CONFIG_SQUASHFS_ZSTD), which the kernels Firecracker’s CI builds do
on both architectures for 5.10, 6.1 and 6.18, the three lines the release
matrix tests. backhand’s zstd is the C library, built into function-oci
alone: the dependency graph of function-wasm has none of it. The format is
part of engine::version(), so a runtime with another packing starts a
new directory of the compiled store and no VM snapshot taken over one
format meets a root filesystem written in the other.
One VM per request. The runtime starts the VM with the kernel, the
root filesystem mounted without write access, a vsock device, memory sized to the step’s
limits.memory plus the kernel’s share, one vCPU (--vm-vcpus) and
the deadline. The init mounts the root filesystem with a tmpfs overlay,
both nosuid and nodev like the fresh /tmp,
brings up loopback and reads the run’s description over vsock (env, user,
cwd, entrypoint and the proxy settings). It starts the process as the
image’s user, never root, and streams its output to the host as it arrives.
The runtime refuses an image that runs as root at load, from the config
alone when the config doesn’t set a user or sets the number 0, before it
unpacks a layer.
Before the exec the init empties the capability bounding set, clears the
ambient, permitted, effective and inheritable sets and sets no_new_privs.
The init is then the guest’s sole root. Dropping capabilities alone isn’t
enough, because UID 0 can still write the cgroup file that caps the run’s memory. Once the function’s port accepts a
connection the init bridges it to a second vsock connection, and the host
calls RunFunction over that, bounded by the run’s deadline and a limit on
the response’s size. The runtime returns the response as soon as it has
it. A thread of its own ends the rest of the run. The init stops the
process and reports its exit, which flushes what it logged. The runtime
logs those lines and the VM’s console. Then it kills and reaps the VM,
which discards every change the run made, and a fresh instance per
request holds. Until 2026-11-13 the caller waited for that work. A CI
runner measured its median at 24 ms of a booted run of 400 ms and at
19 ms of a restored run of 177 ms, 3 to 5 ms of it for the exit report
and the rest for the VMM’s exit. When the function doesn’t answer, the
run is over before its fatal result returns, because the result quotes
how the process ended and what it logged last. --enable-vm-snapshots restores a snapshot of the booted VM in place of
the boot (Snapshots).
Bounds. limits.timeout is the VM’s wall clock, the boot included.
limits.memory is the process’s memory. The init runs it in a cgroup
capped at the limit. The VM gets the limit plus a fixed share for the
kernel, the init and the overlay. The run slots, the fair scheduler by digest, the memory pool,
the step slots and the gRPC deadline cap apply unchanged, because they
wrap Engine::run. A run’s slot and its memory belong to the VM. An
answered run keeps both after the response, until the runtime has reaped
the VMM. The next VM starts when the one before it’s gone, not earlier.
runs_in_flight counts the run until then, and run_duration observes
it at the response, which is what a caller waits. The step slot is the
runtime’s and ends with the call. While the runtime stops one VM of a
step at its limits.concurrency, the step may already run its next,
inside both bounds of the engine. The runtime drops its engine when it shuts down, and a dropped
engine waits until it has stopped every VM, which keeps a shutdown from
leaving a VMM running. The kernel kills a process past its cap. The
init reports the exit, and the fatal states the limit as the Wasmtime
limiter’s does. After the response there’s no result to fail, and the
runtime logs a warning that states the limit.
Egress. The VM has no network interface, and until the proxy exists
function-oci refuses a manifest that requires egress, by name. The proxy
gets a design of its own first, in
#280, before
phase 5. Decision 3 is its direction: the init listens on
127.0.0.1:3128 inside the guest and sets HTTP_PROXY, HTTPS_PROXY and
NO_PROXY= (empty) in the process’s environment. The init decrypts TLS for
https targets with a certificate authority it generates at boot. It
installs that authority where the common runtimes look (SSL_CERT_FILE,
REQUESTS_CA_BUNDLE, NODE_EXTRA_CA_CERTS, /etc/ssl/certs) and relays
each request in the clear over vsock to the host. On the host the run’s
egress client judges it as it judges a component’s. The manifest’s rules on
method, host and path apply, as do the block list per resolved address,
the redirect check per hop, the budgets, the rate limit, the audit line and
the outcome metric. A refusal comes back as an HTTP 502 with the refusal
sentence as its body. Without a requires.egress grant the init skips the
proxy and the variables. A VMM’s own socket forwarding (libkrun’s TSI) is
off: it would give the guest the pod’s network. The design has to answer
what this direction doesn’t, such as the clients the proxy covers, the
authority under --enable-vm-snapshots and the wire between the init and the
host.
Credentials and env. requires.env bindings become process environment
through the init. requires.credentials entries travel in the request,
and the runtime withholds every other step credential before it encodes
the request and sends the bytes to the VM. The
runtime withholds the pull credential from the VM as it does from a
component.
Time and randomness. The guest’s clock comes from the host’s paravirtual clock, its randomness from virtio RNG. Both are what a container gets.
Node requirements. The pod needs /dev/kvm. The install page documents
a device plugin that advertises the node’s /dev/kvm as a resource
(generic-device-plugin) and a DeploymentRuntimeConfig that requests one,
with the kvm group among the container’s supplemental groups. The
runtime refuses to serve with a sentence that states the device when it
can’t open it. The VMM runs as the pod’s user, and the
pod’s cgroup is the jail, without privileged and without
CAP_SYS_ADMIN.
The development loop. The loop runs on a Linux machine with
/dev/kvm, where the runtime boots the VM it boots in the pod.
Firecracker has no macOS port, and a machine without KVM has no loop
(decision 9).
Snapshots
--enable-vm-snapshots restores a snapshot of an image’s booted VM in place of a
boot. It’s a prototype, off by default and Firecracker’s alone, and 0.1
includes it as an alpha feature (decision 13).
Per-image microVM snapshots is its design record.
Offline validation and the CLI
function validate --resolve pulls the artifact and reads the manifest. It
resolves the image digest to the node’s platform and reads the image
config. It checks the contract’s preconditions, that the config has an
entrypoint or a command, that the user resolves and that the platform
exists. It
prints the same admission verdicts as today.
For an OCI module guestfn publishes and inspects, and the author
scaffolds the project and builds the image (decision 12):
| command | oci@0.1 |
|---|---|
guestfn build | refuses an oci@0.1 manifest: the command builds WebAssembly modules, and the author builds the image with docker build (or buildx) |
guestfn push --image <ref@sha256:…> | appends the manifest to the image the author pushed, as one more layer, and writes the image’s digest into the manifest’s oci.image. It doesn’t read a module file |
guestfn inspect | says that a module image is one and which image the manifest records as its origin, with the manifest’s summary. --pull refuses it |
guestfn scaffold composition | unchanged |
An OCI guest is an ordinary function on the language’s own SDK.
examples/function-oci-go is one in Go, with its Dockerfile.
The Input
The module block, compositionPolicy, limits and config keep their
schema. Both packages serve the Input as guestfn.crossplane.io/v1, which
replaces wasm.fn.crossplane.io/v1 outright: the WebAssembly runtime
refuses the old group with a sentence that states the new one, function validate prints the same sentence, and the CRD under package/wasm/input/,
the scaffolds’ compositions, the examples and the goldens move with it.
The v1beta1 deprecation goes with the old group.
Code shape
crates/function: the runtime as a library, generic over the trait.cli.rsis the entry point the two binaries call.manifest.rsgains theContractenum andoci.image.oci.rsreads the wrapping artifact, andresolver.rsfetches an image through it into a layout.crates/engine: theEnginetrait and what the engines share. The writer for the image layout is here soresolver.rscan use it.crates/engine-wasm: the Wasmtime engine.crates/engine-oci: theSandboxtrait with Firecracker behind it (firecracker.rs: the machine config, the devices and the lifecycle),rootfs.rsunpacking the layers into the squashfs root filesystem,layout.rsreading the image layout the runtime hands over,image.rsholding the image config and the run description,initrd.rspacking the initramfs around the init,run.rsapplying the bounds and wording the fatals, with the egress bridge ontoHttpRequesterto come.crates/oci-init, the guest init (guestfn-init, static for musl): it mounts, overlays, starts the process and relays the streams. The proxy with its authority comes with the egress phase.crates/oci-fixtureis the function the VM tests run, andcrates/oci-protocolis what the init and the host say to each other (Description,Exit, the frame kinds), framed over vsock.crates/guestfn:push.rsappends the manifest to an image under--image, andinspect.rsdescribes a module image.buildcmd.rsrefuses anoci@0.1manifest.package/oci/besidepackage/wasm/: one package root per runtime, each with itscrossplane.yamland a copy of the Input CRD.crates/function-oci/Dockerfileadds the VMM and the kernel..github/workflows:build-ocijobs ine2e.yml, anocie2e profile on a KVM runner, andpublish-function.ymlpublishing either package.
Tests
- Unit: the layer unpacking against fixtures with whiteouts and
ownership, read back from the form the sandbox boots. The init protocol
framing. The manifest’s
contract,oci.imageand per-engine rules. The wrapping artifact inpush.rs. - The engine’s VM suite runs a static test image built in the test from a small binary that echoes a fixed response, unpacked and run under the sandbox on a KVM runner. The cases cover the deadline, the memory limit, a non-zero exit, stderr log lines and a proxied request against a fake requester.
- Conformance goldens: a new fixture family for the OCI refusals and the package mismatch sentence.
- The example:
examples/function-oci-gotests its function natively, and thebuild-oci-gojob runs those tests. - End-to-end tests run an
ociprofile with thefunction-ocipackage on kind with/dev/kvmmounted, on a KVM-capable runner, exercising a committed test image through the same Guest XR.
Documentation
An operators page for the OCI runtime (install, the device and the flags),
a guests page for the contract and for publishing an image as a
module, the manifest page’s contract and oci.image fields, the artifact’s
media types on the trust model page, the Input reference’s apiVersion
note, and the troubleshooting entries for the new refusals.
Compatibility
The project is at 0.6, and the owner accepts the breaks below before 1.0 (2026-11-05). The WebAssembly runtime’s admission, wording, flags and metrics don’t change otherwise.
| today | after | who moves |
|---|---|---|
wasmfn.yaml | guestfn.yaml | the scaffolds, the examples, the goldens, module.manifestPath users |
application/vnd.wasmfn.manifest.v1+json | application/vnd.guestfn.manifest.v1+json | every published artifact, by a new push |
wasm.fn.crossplane.io/v1 (and v1beta1) | guestfn.crossplane.io/v1 | every Composition’s Input, the CRD under package/wasm/input/ |
The runtime refuses the old names with a sentence that states the new one,
and function validate prints the same sentence. The function-oci
package starts alpha, on its own tags and releases (decision 15).
Alternatives
-
gVisor as the sandbox. A user-space kernel, with no KVM required on its systrap platform, slower system calls and a boundary made of software alone. A later sandbox behind the same
Sandboxtrait if a cluster can’t offer KVM. -
A libkrun prototype and a comparison. A libkrun and a Firecracker prototype behind one
Sandboxseam. Dropped from the path to 0.1 (Jonasz, 2026-11-09), with Firecracker staying for now. -
Kata Containers through a RuntimeClass. The runtime would create a Pod per request and talk to it. Seconds of latency per request, RBAC to create Pods and no
crossplane render. Rejected. -
Edera. A Xen-based hypervisor, with its control plane in Rust, that gives each pod its own microVM and kernel through a RuntimeClass. The node boots into Edera’s hypervisor, which is the operator’s platform decision, and the open source part, krata (the Xen control plane, GPL-2.0), is a component of the commercial Edera Protect. The function pod can’t embed it, and a zone contains a whole pod. Rejected as the runtime’s sandbox for the same reason as Kata. An operator who runs the runtime pod itself under an Edera RuntimeClass adds a second boundary around the whole runtime, which this record neither needs nor prevents.
-
A plain OCI runtime (crun, youki) as the production sandbox. Shares the host kernel. A development fallback at most, which decision 9 leaves open, since Firecracker has no macOS port.
-
A process contract over the standard streams. The first build ran the image’s command once per request with the request on standard input and the response on standard output. An SDK image needed an adapter around its server. Replaced before any release (Jonasz, 2026-11-09, #258).
-
The manifest as an OCI 1.1 referrer of the image. Standard, but the signature on the image wouldn’t cover the manifest, the manifest would need its own signature, and the Input would pin the image rather than the manifest. The appended layer keeps one pinned digest and one signature.
-
A wrapping artifact beside the image. The first build published the manifest as the one layer of an artifact of its own (
artifactTypeapplication/vnd.guestfn.module.v1over the empty config) whose manifest pinned the image. One pinned digest and one signature too, but a second repository to name and sign and a second pull on every cold load, and no container runtime could run the artifact. The owner chose the appended layer on 2026-11-08 (decision 11). -
The manifest as a plain file inside the image. Reading it needs a pull of the layers, and admission couldn’t refuse before the fetch. The annotated layer is that file, found through the manifest and read on its own.
-
An ext4 image as the root filesystem. The first draft’s form for a VMM with block devices alone. A squashfs writer keeps the ownership without root, and the guest mounts the image without write access under its overlay, the unwritable root the design describes. The build writes squashfs.
-
The VM’s memory as the process’s limit. The first build sized the VM to
limits.memoryalone. Without swap the guest kernel thrashed its page cache for the whole budget before its killer acted. The cgroup cap inside the VM ends the process at once. -
A
hostPathmount of/dev/kvm. The first draft’s recipe for the pod. It puts the device node in the container but not in its device cgroup, so everyopenfails withOperation not permittedin an unprivileged pod, the runtime exits at startup and Crossplane’s gRPC client finds the function’s headless Service empty, which the e2e profile’s first run showed. The device plugin admits the device, and the operator page keeps the symptom for the reader who meets it. -
OCI scaffolds and an image build in
guestfn.guestfn init --type oci --lang go|python|rust|tswould write a project with aDockerfile, amainthat reads stdin and writes stdout around the language’s function SDK, unit tests that run natively and aguestfn.yamlwithcontract: oci@0.1.guestfn buildwould rundocker buildand then a contract check, which is one run of the image under the sandbox with an empty request and a verdict on whether stdout decoded as a response. The guest suite would run each scaffold through the whole host on a KVM runner. Dropped (Jonasz, 2026-11-09): scaffolding and building the image are the author’s, andguestfn push --imagewraps the result with the manifest layer. -
A separate repository. The policy, proxy and tooling code is most of the product and changes together. Rejected.
-
One engine crate with a Cargo feature per engine. The first build’s shape. With both features on
wasmserved, so the workspace’s lint and tests never compiled thefunction-ocibuild (decision 1). -
A container sandbox for machines without KVM. A sandbox behind
--insecurewould run the image through the Docker daemon or a rootlesscrun, with the same init protocol over a Unix socket and a warning at startup and under every stepfunction validateprints. It would give a machine without KVM a development loop, and 0.1 goes without it (decision 9).
Decisions
The owner settled these on 2026-11-05:
- Packaging. Separate packages from one workspace, each a binary crate
over the generic runtime, with a crate per engine (Jonasz, 2026-11-09,
after Cargo features that exclude each other).
function-wasmkeeps its size and runs without a device.function-ocineeds/dev/kvm. - The contract. A gRPC server in the VM: the image is an ordinary
Crossplane function, and the host calls it over vsock (Jonasz,
2026-11-09, #258).
The manifest nests keys specific to a contract under its name:
oci.imageandoci.args. - Egress. A TLS-decrypting proxy in the init with a per-run authority, for full rule parity on method and path.
- The manifest’s placement. A layer of the image, found by its annotation (first a wrapping artifact, revised by decision 11).
- Names. The
guestfnnamespace:guestfn.yaml, the media types undervnd.guestfn, the Input groupguestfn.crossplane.io/v1, with no alias for the old names (the project is at 0.x). - The Input. One generic group for both packages, replacing
wasm.fn.crossplane.io/v1. - Order. The trait, the manifest and the tooling, the init protocol, then the microVM sandbox.
The owner decided this on 2026-11-06:
- The contract field. The manifest’s
abibecomescontract, an enum written<engine>@<major>.<minor>with no alias:wasm@1.0is the component world,oci@0.1the contract of an image, andtypegoes, since the contract states the engine. From a contract’s 1.0 a minor adds fields a module may use between versions and a major changes what the engine does with a module, and at 0.x a minor may change anything. The runtime refuses the old name as an unknown field.
The owner decided this on 2026-11-08:
- The appended layer.
guestfn push --imageappends the manifest to the image as one more layer, the way Crossplane’sxpkg appendadds a package’s extensions, instead of publishing a wrapping artifact beside it. The image remains runnable and the module’s digest covers image and manifest, with one repository to name and sign.
The owner decided this on 2026-11-09:
- The sandbox. Firecracker stays for now. The libkrun prototype and the comparison are off the path to 0.1, under Alternatives. The decision isn’t a final verdict on the sandbox.
The owner decided these the same day:
- The CLI. Scaffolding and building the image are the author’s.
guestfn push --imagepublishes the image with the manifest appended as a layer (decision 11), andguestfn inspectandfunction validate --resolveread what it published. The OCI scaffolds and the image build inguestfnare under Alternatives. - Snapshots. A snapshot belongs to one image and has the image
and the VM size as its key. Restores go through the API of the release
binary. 0.1 includes snapshots as an alpha feature behind
--enable-vm-snapshots. Per-image microVM snapshots has the design and the image-independent snapshot it rejected. - The egress design. The proxy gets a design of its own first, in #280, before phase 5. Decision 3 remains its direction, and the design enforces the manifest’s method and path rules. 0.1 doesn’t wait for the proxy: it refuses a manifest that requires egress, by name.
- Tags and releases. Each component has its own: git tags and GitHub
releases named
function-wasm-vX.Y.Z,function-oci-vX.Y.Z,guestfn-vX.Y.Zandwit-vX.Y.Z, and release branches namedrelease-<component>-X.Y. The tag of an OCI artifact drops the prefix and keeps the version. - Compatibility at 0.x. Until function-oci’s 1.0.0 a release may
break anything the package has, and it announces a rename or a
removal by refusing the old name by name. The wording of a fatal
result is never a contract. The contract is
oci@0.1while function-oci is 0.x: a minor version may break images built for the one before, andoci@1.0comes with function-oci’s 1.0.0. Whether the Input, the manifest and the metric names are stable for function-oci waits for function-wasm’s 1.0.0 (Compatibility).
The owner decided this the same day:
- The development loop without KVM. Firecracker has no macOS port, and a machine without KVM has no loop. 0.1 has no container fallback and runs on KVM alone.
The owner decided this on 2026-11-12:
- An unprivileged process. The runtime refuses an image that runs as
root, and the init drops every capability and sets
no_new_privsbefore it starts the process. The process then can’t read or change what belongs to the init, which the egress proxy (#280) depends on.
The owner decided these on 2026-11-13, with the measurements of #376:
- zstd for the root filesystem. The runtime packs the squashfs with zstd in place of gzip, and function-oci accepts the C library that comes with it. function-wasm doesn’t get it.
- The response before the teardown. A caller gets its response before the runtime has stopped the VM. The run’s slot and its memory remain the VM’s until the runtime has reaped the VMM.
Phases
#281 has the order from these phases to 0.1, the package’s first release.
- Done (#247). The
Enginetrait started in its own crate. On 2026-11-06 it moved back intocrates/engineat the owner’s ask, and each engine has had a crate of its own since 2026-11-09.crates/functionis generic over it, with Wasmtime behind it and the behaviour and the goldens unchanged. - Done. #244 renamed the manifest file and the media type. #246
moved the Input group and generated the CRD. #247 added the manifest’s
typewith its per-type contract, withtype: ocirefused by name. The next PR madeabithecontractenum and added the manifest’soci.imagewithguestfn push --image, which first published a wrapping artifact and now appends the manifest to the image as a layer (decision 11), read back byguestfn inspect. - Done, on Firecracker, covering the OCI engine behind the
Sandboxtrait, the init and its protocol, the layer unpacking into squashfs, the VM lifecycle, the bounds,function validate --resolvefor images, thefunction-ocibinary with its flags, the image fetch of the resolver with the manifest read out of the image’s annotated layer, and the env bindings and the credentials through the init. - Done, namely the
ocie2e profiles on a GitHub runner with KVM, as the jobs ofe2e-oci.ymlbeside thewasmones (a build job and a cluster job per profile) and the engine’s VM suite inci.yml, with the published kernel. The kernel build, where the project builds its own, remains open. - The egress bridge (the TLS-decrypting proxy in the init) with audit and
metrics parity, after its design in
#280 (decision
14). Until then
function-ocirefuses a manifest that requires egress, by name. - Done in part (#263):
examples/function-oci-go, the hello function as an image on the contract, published bypublish-examples.ymlthroughdocker buildxandguestfn push --image, and theocie2e case that pulls the published example fromghcr.io. Thefunction-ocipackage’s publish workflow (Publish Function, withfunction-ocichosen), its image (crates/function-oci/Dockerfile), its package root (package/oci) and its operators page are in the tree. Left: the package’s first release, 0.1.0. - A prototype (#255):
snapshots per image behind
--enable-vm-snapshots(Per-image microVM snapshots), in 0.1 as an alpha feature (decision 13).
Per-image microVM snapshots
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: draft (an alpha feature in 0.1 behind
--enable-vm-snapshots, off by default)
function-oci boots a microVM for each request
(OCI runtime), and the boot is most of a short
run: the kernel start, the mounts and the vsock connect come before the
process does anything. With --enable-vm-snapshots the runtime boots an image’s
VM once and freezes it where the init waits for a run. Each later request
gets a fresh VM restored from that snapshot. Fresh instance per request
still holds: a clone runs one process, and the runtime kills the clone with
the run.
The feature is Firecracker’s alone, since libkrun has no snapshots.
Design
Taking a snapshot
The first run of an image at a VM size boots the VM as before, except that
firecracker starts with --api-sock beside its configuration file. The
init mounts the root filesystem, connects to the host over vsock and says
hello. The host answers Park in place of the run. The init answers
Parked and blocks reading that connection, with nothing in flight. The
host then pauses the VM (PATCH /vm) and has Firecracker write a state
file and a memory file (PUT /snapshot/create). It kills the VM once the
files exist, before the VM runs a process or receives a request, an
environment binding or a credential. A snapshot contains the booted kernel,
the init and the mounted root filesystem.
Firecracker writes each page of the VM’s memory, and most pages of a booted guest are zero. The engine rewrites the memory file sparse: it skips each 64 KiB block of zeros, and a hole reads back as zeros when the restore maps the file.
Restoring
A later run of the same image and VM size starts a fresh firecracker with
--api-sock and loads the snapshot (PUT /snapshot/load). The load sets
the run’s own vsock socket (vsock_override), maps the memory file
privately and resumes the VM. Firecracker resets the guest’s vsock
connections across a snapshot: it queues the reset when it writes the
snapshot, and the guest’s driver handles it when the VM resumes. That reset ends the
read the parked init blocks in. The init connects to the clone’s host and
says hello as it does after a boot, and the host sends the run. From there
the run uses the booted run’s code, with its frames and its fatal wording.
When the host can’t make a snapshot, it logs a warning and boots the VM for
that run. A boot with the flag off still starts firecracker with
--no-api. Firecracker takes and loads a snapshot through its API alone,
and these two paths open the socket for it. The socket is in the run’s
private directory, and the release binary keeps its seccomp filters.
Warm-up and first runs
Warm-up takes the snapshot of each --warm-modules image before the pod
reports ready, for the VM a step with no limits.memory of its own gets.
The first request of a warmed image then restores. An image the warm-up
didn’t load gets its snapshot at its first run, and a step with its own
limits.memory gets one at the first run with that limit.
A run doesn’t wait for a snapshot another run is making, because making one takes longer than a boot: 1.5 s against 1.1 s in the measurements. A run that finds the snapshot in the making boots, as it would with the flag off, and no request waits past its deadline for the snapshot of another.
A VM reserves its whole memory from --max-total-run-memory before a
restore as before a boot. A restored firecracker resided at 20.6 MiB
after the echo run, but the guest may use its whole memory, and the pool
counts that ceiling.
Freshness of a clone
A clone’s memory is a private copy-on-write mapping of the memory file. The
overlay’s upper layer and /tmp are tmpfs inside that memory, empty at the
snapshot. A clone’s writes stay in the clone, and three clones in a row
each found the files of the one before absent.
The wall clock and the kernel’s random state come from the snapshot. For a restored run the description includes the host’s time and 32 random bytes. A parked init sets the clock from the time and reseeds the kernel with the bytes before it starts the process.
- On arm64 a clone’s wall clock continues from the snapshot’s moment. With the refresh off, a clone restored five seconds after its snapshot read five seconds behind the host. With it on, the clone read within a second of the host.
- With the seed off, five clones still drew five different values from
/dev/urandom, probably through the VMGenID device, which Firecracker updates on a restore. The seed covers a guest kernel without that device.
Clones of one snapshot share the kernel’s address layout, the kernel secrets from before the park, the monotonic clock’s starting value and the sequence of process IDs. Those clones all run one module, which limits the exposure to a module’s view of its own earlier runs.
The key
A snapshot restores into the memory size and the vCPU count it came
from, and into no other. A step’s limits.memory sizes the VM: the VM gets that limit plus
64 MiB for the kernel. That makes the key an image, a VM memory size and a
vCPU count. The vCPU count is the operator’s --vm-vcpus, one value for
the runtime, which leaves limits.memory as what multiplies an image’s
snapshots.
In the compiled store
The runtime keeps a snapshot beside the image’s root filesystem in the
compiled store, compiled/<version>/. It’s a state file and a memory file.
Their names start with the entry name of the root filesystem and go on
with the VM’s memory size, its vCPU count and a fingerprint of the
Firecracker binary, the guest kernel, the init and the boot arguments. A
different Firecracker, kernel or init looks under another name. The
<version> of the directory includes the format of the root filesystem.
A runtime that packs the root filesystem another way starts a new
directory, which keeps a snapshot apart from a root filesystem in a
format the snapshot didn’t come from.
Firecracker writes both files in place, since a VM’s memory is too large to
hand over as bytes. The store signs a file under its per-process key once
the file is complete
(Compiled-artifact cache key). An unfinished file
is no entry. The engine removes the files of a snapshot it couldn’t finish,
and the runtime removes what an interrupted write left when it starts. The
sweep bounds the snapshots with the store’s other entries, and
the cache_bytes gauge counts them. Both count a sparse file by what the
disk allocated for it.
A loaded image remembers its snapshots while it stays in memory. When the runtime loads the image again, the engine looks the snapshot up in the store, which verifies the signature over the whole file as it does for the root filesystem. The engine makes a snapshot again when the store refuses it or the sweep removed it from under a loaded image. When the engine can’t make or restore a snapshot, that run boots, and the image goes without snapshots until the runtime loads it again.
A compiled image first runs from a scratch file. Once the runtime has
stored the root filesystem, the engine continues from the stored file
(Engine::stored), because a snapshot records the path of the drive it
mounted and a stored file keeps its path. The engine pins the stored
root filesystem of a loaded image, and the sweep skips a pinned file. Each run marks the root
filesystem and the snapshot it restores as used, which keeps the snapshot
of a busy image out of the sweep. An image the runtime didn’t store keeps its
snapshots in the engine’s scratch directory while it stays in memory, and
the engine removes them when the image leaves.
The protocol
Park (host to init, in place of Run) and Parked (the answer) are new
frame kinds. The description gains now_unix_ns and seed, both empty for
a booted run. The init and the engine come from one image.
Measurements
Most numbers come from one machine: a laptop’s nested KVM (arm64), Firecracker 1.17.0, the pinned 6.18 guest kernel, one vCPU, the default 512 MiB limit and with it a 576 MiB VM, the echo fixture, 30 runs for each path after one warm-up run.
| boot | restore | |
|---|---|---|
| the whole run, median | 1123 ms | 250 ms |
| the fastest and the slowest run | 1112 and 1152 ms | 241 and 256 ms |
firecracker starts, and loads the snapshot | 0.2 ms | 3.1 ms |
| until the init connects | 1030 ms | 36 ms |
| the protocol and the process | 85 ms | 206 ms |
firecracker’s resident memory at the exit | 49.7 MiB | 20.6 MiB |
firecracker’s minor page faults | 12203 | 1086 |
The first run of an image takes 1.75 s with snapshots on: the boot, then about 0.6 s to write the memory file and rewrite it sparse. That file is 576 MiB long and 44 MiB on disk, and the state file is 6 KiB. The second request of an image saves more than the snapshot cost. With the snapshot taken at warm-up, the first run of the image took 252 ms.
A clone runs its process slower than a booted VM does, because each page it
touches faults in from the memory file. Nested virtualization makes a fault
and a boot expensive: a boot on this machine takes four times the 270 ms a
CI runner measured. The ratio between the two paths transfers better than
the milliseconds do. The VM suite prints both paths’ times, and
boot_against_restore in crates/engine-oci/tests/vm.rs is the benchmark,
run by hand.
On GitHub’s runners (x86-64) the VM suite ran twice on 2026-11-09, on Firecracker 1.18.0 and on 1.17.0. A boot run took 297 and 350 ms, and a restored run 87 and 122 ms. The first run after a warm-up took 122 ms in the second. The run that made the snapshot took 5.0 and 4.4 s, against 1.75 s on the laptop: the 576 MiB memory file costs the runner’s disk 4.0 to 4.7 s to write and rewrite. A restored run saves 210 to 230 ms there, and the snapshot’s cost equals that saving over about twenty requests, which is the case for taking it at warm-up.
Decisions
Jonasz settled these on 2026-11-09, with these measurements:
- The prototype merges behind a flag, off by default, and #279 continues from it.
- Snapshots are in 0.1 as an alpha feature, and the flag is
--enable-vm-snapshots. It’s off by default in alpha and on by default in beta and later. - Alpha accepts the 4 s or more the memory file of a snapshot takes on a GitHub runner: warm-up pays it before the pod reports ready, and a restored run saves 210 to 230 ms there.
- A snapshot belongs to one image. Its key is the image and the VM size,
since
limits.memoryresizes the VM. - Restore goes through the release binary’s API socket, and the engine
keeps forking
firecracker. That answers the question #265 left to this work.
Alternatives
- An image-independent snapshot. One generic VM frozen before it mounts a root filesystem, with the drive pointed at the request’s squashfs after each restore. It trades one memory file for the whole runtime against the mounts and two more API calls per request. Nobody measured it. Rejected (Jonasz, 2026-11-09): a snapshot is per image.
- A parked init that listens. Firecracker keeps a guest’s listening sockets across a restore, and the issue’s first sketch had the host connect to the init. The guest closes its connections when it handles the pending reset. A host that connects before that can lose its connection, and the host would need a retry. The driver’s code suggests this, and nothing reproduced it. Waiting on the open connection doesn’t need a retry and reuses the boot’s accept path.
- A parked init that polls. The first version closed its connection and tried to connect each 2 ms until a clone’s host answered. A snapshot can catch a connect in flight, and each clone of that snapshot could then wait out the 2 s connect timeout.
- One VM size per image. The runtime would snapshot at its memory ceiling and leave the limiting to the process’s cgroup. That gives one snapshot per image, and the memory pool would reserve the ceiling for each run. A second size costs 44 MiB with sparse files.
- Firecracker’s
vmmcrate in the engine. #265 measured it. Restore works there and the whole run takes as long. The crate has no seccomp filters, and a VMM in the runtime’s address space shares the runtime’s fate. The release binary’s API answers a load about 3 ms after the process starts. - A
userfaultfdhandler. Firecracker can hand a clone’s page faults to a handler that could load the recorded working set at once, although the measured gain doesn’t need it. A restored run on a GitHub runner took 87 and 122 ms against 297 and 350 ms for a boot.
Read fence
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.0 (a
requireResourceaction over the response’s requirements, for finding F-6 of the 1.0 security audit, #208; the owner settled the open points on 2026-11-05)
Summary
composeResource fences what a module writes to the desired state. Through
the response’s requirements a module requests any resource the Function’s
RBAC lets Crossplane read, as a native function can, and the runtime relays
the selectors without reading them. Crossplane then fetches cluster data the
sandbox never exposes and sends it to the module in the next request’s
required_resources. No policy rule judges that request today. The
Function’s RBAC is the one fence, and RBAC is per Function, never per
Composition or per tenant.
This record adds a tenth Cedar action, requireResource. The runtime judges
every resource selector of a response in both policy layers, scoped
default-permit in each, over the entities composeResource uses and with a
refusal sentence of the same form. The runtime judges the selectors because
the selectors are what it sees. Crossplane reads the resources themselves
after the response and sends them to the module in a later request. The
manifest gains an advisory requires.resources declaration, for the
tooling.
Design
The action
requireResource takes a Kind resource in the Group hierarchy
composeResource uses: Kind::"<group>/<Kind>" from the selector’s
apiVersion and kind, the core group spelled core, the version dropped,
resource in Group::"apps" true for every kind of the group. The context
describes the selector:
| attribute | present | value |
|---|---|---|
context.name | for a match by name | the selector’s matchName |
context.labels | for a match by labels | a record of the selector’s labels, label keys as attributes, so context.labels has team and context.labels["app.kubernetes.io/part-of"] == "x" both read |
context.namespace | when the selector sets one | the selector’s namespace |
An attribute the selector doesn’t set is absent, never empty, and a
selector matches by name or by labels, never both. Test an attribute with
has first, as spendCredential rules test context.repository. Cedar
treats a rule that reads an absent attribute as unmatched, which turns a
forbid into no fence. The Cedar page says so beside the worked example.
The principal is Request::"self" as for every action. A tenancy rule
reads context has namespace && context.namespace == principal.namespace.
The selectors
After the run, over the response the runner decoded for the output fence,
the runtime reads every ResourceSelector in requirements.resources and
in the deprecated requirements.extra_resources. Crossplane still serves
the deprecated map, and a module could otherwise use it to step around the
fence. The selectors of each map come in key order, the current map first, so
the first refusal is the same on every reconcile. The response’s bytes
don’t change.
A selector with no apiVersion or no kind matches no rule. Where a layer
scopes the action the runtime refuses such a selector with its own
sentence, as the output fence refuses a composed resource with no kind.
Where no layer scopes the action the runtime relays it as today, and
Crossplane answers it.
The runtime judges the selectors on every response, one with a fatal result included. The output fence skips such a response because Crossplane applies none of its desired state, and the guest’s own message stays the one the author reads. A selector is a request the proxy relays whatever the results say. Whether Crossplane acts on the selectors of a fatal response is Crossplane’s choice, which may change between its minors. A refused selector replaces the guest’s fatal result with the runtime’s, which states the cause the author fixes first.
The runtime judges the selectors before it diffs the desired state. A response with a refused selector and a refused kind reports the selector. The order follows the module’s logic, where the read precedes the write, and the cheaper judgment runs first.
requirements.schemas, the CRD schemas a module may request, remains
unfenced. A schema is public metadata of a kind. The request’s
required_resources keeps its bytes too. It contains what Crossplane
fetched for a selector the runtime permitted on the previous call.
Evaluation
Both layers judge the action as they judge composeResource:
- scoped default-permit in each layer: a layer narrows the reads where
one of its rules spells the action, and a
forbidalone permits nothing - the composition layer first and whole, then the operator’s, with the refusal stating the layer
The operator layer keeps the scoped default-permit here for the reason the output fence recorded. No rule judged the selectors before this change. A default-deny would refuse, on upgrade, every module that requests an EnvironmentConfig, the function-wasm-ts example included. A runtime with no policy file and a Composition with no rule for the action pay one boolean per response.
A refusal is a fatal result on a fresh response, counted as
requests_total{outcome="refused"} and prefixed with the module as every
refusal is:
- by name:
module oci …: required core/Secret "db-password" in namespace "team-b" (requirements.resources["db"]), which the compositionPolicy does not permit (requireResource) - by labels:
module oci …: required core/Secret with labels team=a,tier=gold (requirements.resources["secrets"]), which the operator policy (--sandbox-policy-file) does not permit (requireResource) - a selector no rule can judge:
module oci …: required resource "db" states no apiVersion or kind, so the policy layers cannot judge it (requireResource)
The in namespace clause appears when the selector sets one, the labels
come in key order, and the sentence spells the map as the response did.
requests_total already counts a refused request, which is the one
metric the fence needs.
Offline validation
function validate can’t judge a selector offline any more than it can
judge output. It marks a step whose compositionPolicy scopes the action
with requireResource on its OK line and in the JSON admitted list,
beside composeResource.
The manifest’s requires.resources declaration
A manifest declares what the module asks Crossplane for under requires,
beside the capabilities it needs (Jonasz, 2026-11-05: under requires, not
a top-level reads):
requires:
resources:
- kind: apiextensions.crossplane.io/EnvironmentConfig # <group>/<Kind>, the core group spelled core
by: [name] # name, labels; both when omitted
The declaration is advisory, as composes is, and unlike the other
requires entries the runtime never grants or refuses it before the run. The fence
judges the actual selectors after the run regardless of the declaration,
because a manifest requests and never grants. The tooling reads it in the
three places that read composes:
function validate --resolvewarns where a layer would refuse a declared kind:the module declares it requires apiextensions.crossplane.io/EnvironmentConfig (by name), which the compositionPolicy does not permit (requireResource). The offline judgment evaluates a read by name withcontext.nameempty and a read by labels withcontext.labelsempty, and never setscontext.namespace, so a rule conditioned on a value may warn for a selector the run would permit. The warning is advisory, as thecomposeswarning is.guestfn inspectshows it in the manifest summary, asresources <kinds>.guestfn scaffold compositionwrites onerequireResourcepermit per declared kind into thecompositionPolicyskeleton, withcontext has nameorcontext has labelsfromby.
guestfn build and guestfn manifest validate refuse a kind that isn’t
<group>/<Kind>, a by entry other than name and labels, and an
unknown field inside an entry, the strict decode the rest of requires
gets. The function-wasm-ts
example and the end-to-end guest declare their EnvironmentConfig read, the
example’s version bumped so the published artifact contains it.
A worked example
A Composition whose module reads the EnvironmentConfig its XR specifies:
permit (principal, action == Action::"requireResource",
resource == Kind::"apiextensions.crossplane.io/EnvironmentConfig")
when { context has name };
An operator who keeps every module’s reads inside the tenant’s namespace, with the cluster-scoped Crossplane kinds open:
forbid (principal, action == Action::"requireResource", resource)
when { resource == Kind::"core/Secret" };
permit (principal, action == Action::"requireResource", resource)
when { context has namespace && context.namespace == principal.namespace };
permit (principal, action == Action::"requireResource",
resource in Group::"apiextensions.crossplane.io");
The first rule keeps Secrets off limits for every module, the second lets a
module read its own namespace and the third opens the cluster-scoped
Crossplane kinds. A selector that omits the namespace and selects a
namespaced kind matches no permit, so a module can’t read across
namespaces by leaving the field out.
Code shape
crates/function/src/authz.rs gains the action name, the Requirement
type (group, kind, the match as a name or a sorted label map, the optional
namespace, and the map and key it came from, for the sentence), its context
builder and a permits_require on both policies over the existing
kind_entities. The operator policy’s scopes_compose boolean becomes the
same per-action map the composition policy keeps, so both expose
scopes_action.
A new crates/function/src/require.rs is the pure half, beside
compose.rs. It turns the selectors of a decoded RunFunctionResponse
into Requirements in judging order, or returns the error for a selector
no rule can judge. It’s plain Rust over the prost types, with authz.rs
keeping the Cedar import, and its tests run without an engine. compose::group_of reads the apiVersion.
crates/function/src/admission.rs gains require_fenced,
require_refused_by, admit_require and describe_requirement, mirroring
their compose twins, with the layer naming shared. runner.rs calls them
after the response decode and before the output fence, under the same
tracing::debug! of what it judges. validate.rs adds the marker and the
advisory loop over the manifest’s requires.resources, beside the one over
composes.
crates/function/src/manifest.rs gains the RequiredResource type
(kind, by) under Requires, its validation, its strict decode with the
rest of requires and its place in the summary. crates/guestfn/src/composition.rs writes the skeleton
permits from it.
Tests
authz.rs: the hierarchy overKindandGroupfor the new action and the three context attributes with and withouthas. It also covers aforbidby itself and the operator layer scoping when a rule spells the action and not before. -require.rs: both maps in key order and the core group. It also covers a selector with no kind and a response with no requirements.admission.rs: the layer stated in each sentence, and an unscoped layer narrowing nothing.manifest.rs:requires.resourcesparsed, validated and refused for a bad kind, a badbyand an unknown field, and shown in the summary.runner.rs: afixed_componentguest returning a response with selectors that one policy admits and another refuses, with the fatal-result case judged and therefusedoutcome counted.- Conformance: a
require.yamlfixture besidecompose.yamlwhose first step scopes the action, withrequire-ceiling.cedarand theRequireResource,RequireResource-jsonandRequireResource-OperatorCeilinggoldens, recorded on purpose, plus theRequireResource-DeclaredandRequireResource-DeclaredCeilinggoldens for the advisory warning under--resolve, ascomposeshas. guestfn: the scaffold-composition golden with a manifest that declares reads, andinspectshowing them.- End to end, default profile: the guest’s
requirementsknob under acompositionPolicythat forbids the EnvironmentConfig kind, expecting the fatal sentence and nostatus.environmentConfig. The existing round-trip test beside it gains apermitto prove the admitted path. Strict profile: the operator policy scopes the action to the tenant’s namespace and refuses the same ask with its own sentence.
Documentation
docs/operators/cedar-policy.md gets the action in the layers and actions
tables, a “The read fence” section replacing the paragraph that proposes
it, the worked example and the refusal rows. trust-model.md, AGENTS.md
and the one-pager on three-layer authorization lose the sentence that
states the gap and count ten actions. troubleshooting.md gets the two
sentences, how-a-request-runs.md the step and docs/project/testing.md
the cluster case. docs/guests/module-manifests.md gets a “The
requires.resources declaration” section beside the composes one, and the
module manifest one-pager a revision for the field.
Compatibility
An added action is what a minor may add under the compatibility promise. A
policy that doesn’t spell it decides nothing new, the Input doesn’t change
and no existing sentence changes. The new sentences join the goldens. A
policy that already spelled requireResource in a rule starts to narrow
reads on upgrade, which is what its author wrote.
Alternatives
- Judging the delivered resources in the next request’s
required_resources. Rejected. Crossplane has read them by then, and the proxy would have to edit the request to withhold them, against the design that forwards the caller’s bytes. - Default-deny in the operator layer. Rejected for the reason recorded for the output fence. The modules that read an EnvironmentConfig today, the function-wasm-ts example and the end-to-end guest, would stop on upgrade.
- Labels as a set of
key=valuestrings. Rejected. A record keepshasand equality natural, and a set would make a rule parse strings. - Skipping a response with a fatal result, as the output fence does. Rejected. The selector travels either way.
- Releasing the fence without the manifest’s declaration and adding it in a
later minor. Rejected (Jonasz, 2026-11-05). The tooling that reads
composesreads the declaration the same way, and a module author who declares what the module composes expects to declare what it requires beside it. - A top-level
readsfield for the declaration. Rejected (Jonasz, 2026-11-05) forrequires.resources: what a module asks Crossplane for is something it requires, named as the proto names it. The author’srequiresblock is the one place that lists what the module needs. - Fencing
requirements.schemas. Non-goal (Jonasz, 2026-11-05). A schema is public metadata, and the runtime relays a schema request as before.
Decision
Jonasz settled the four open points on 2026-11-05.
- The runtime judges the selectors of a response with a fatal result.
- The runtime judges the deprecated
extra_resourcesmap besideresources. - The manifest’s declaration, as
requires.resources, is part of the same release as the fence. requirements.schemasremains unfenced.
Implemented on 2026-11-05 (#233), with the other audit findings of #204 closed before 1.0.0.
Runtime resource governance
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.8 (revision 1.8 holds a run to the wall clock while its guest waits in a host call, and bounds a
wasi:httprequest body; the per-run ceiling is checked over every region together, not per region; a cold load bounded by--module-compile-timeout, the 1.0 audit’s F-4; table growth charged to the ceiling and the pool like memory growth, the 1.0 audit’s F-1; rewritten in the present tense over the Rust workspace; merges in the governance-perf record, revision 0.2: the egress rate limit and the fair run slots are part of the model, and its dropped fuel phase is under Alternatives)
One runtime serves any number of Compositions, teams and modules. This document is the model of what a module may consume, what bounds the runtime as a whole, how the bounds divide the runtime between modules, and how an operator sizes and probes it. The limits exist so that one team’s module can’t take every other team’s reconcile down with it.
Every ceiling is a runtime flag the operator sets. A Composition may lower a
ceiling through the Input’s limits and can’t raise it (the
module source schema defines the fields).
The runtime reads limits from the Input alone, never through module.from, so
an XR author can’t widen a budget. A value over its ceiling is a fatal result
that states both, checked before anything is resolved or fetched:
limits.timeout 1m0s exceeds the runtime's --module-timeout of 30s,
limits.memory 1Gi exceeds the runtime's --module-memory-limit of 512Mi. The
exception is limits.concurrency, which has no ceiling of its own and is
capped to --max-concurrent-runs without a message.
Background
A first request for a large guest costs seconds of CPU and about a gigabyte of peak memory to compile (sizing has the measurements), and the run itself costs far less. Without bounds, N cold requests would run N compiles at once and every module used within ten minutes would stay resident. Every version ever served would also stay on disk. A pod with a core or two serving twenty large modules from a cold cache wouldn’t converge: it would be killed for memory, restart with an empty cache and begin again.
The model
| dimension | bound | flag or Input field | default | at the bound |
|---|---|---|---|---|
| one run, wall clock | epoch deadline over guest code and a wall-clock timer over a guest suspended in a host call, or the request’s gRPC deadline when that’s sooner | --module-timeout; limits.timeout narrows it | 30 s | the run is interrupted and the fatal result states the module and the budget |
| one run, guest memory | Wasmtime store limiter over the run’s linear memories and tables together, a host pointer per table element | --module-memory-limit; limits.memory narrows it | 512 MB | memory.grow or table.grow fails and the guest decides; counted in memory_denials_total{reason="limit"} |
| one run, call stack | Wasmtime’s stack ceiling, engine-wide | --module-stack-limit | 512 KB | the guest traps: a fatal result |
| resident compiled modules | LRU over the memory tier, on top of its 10-minute idle TTL | --max-cached-modules | 0 (TTL alone) | the module idle longest is dropped |
| the memory tier itself | off maps the artifact per request and releases it | --enable-memory-cache | true | nothing stays resident |
| concurrent compiles | semaphore around fetch and compile | --max-concurrent-compiles | 1 | further first requests, and those waiting on the same load, queue |
| one cold load, wall clock | tokio::time::timeout around the load’s thread | --module-compile-timeout | 0s (unbounded) | the request fails with a fatal result that states the bound; the compile finishes on its thread, keeps its slot until then and stores its artifact; counted in cache_events_total{cache="compiled",event="timeout"} |
| disk | LRU sweep over the stores, a read counting as a use | --max-cache-size | 0 (unbounded) | entries removed down to nine tenths of the bound, at startup and every ten minutes |
| module size | cap on fetched bytes, and on tar extraction at eight times the cap | --module-size-limit | 128 MB | the fetch fails: a fatal result |
| concurrent runs | fair run slots, taken after the module is loaded | --max-concurrent-runs | 0 (the caller’s concurrency) | a further request waits under its own deadline |
| concurrent runs of one step | per-digest semaphore, taken before the global slot | limits.concurrency | 0 (the global bound alone) | a further request of this step waits under its own deadline |
| total run memory | pool charged as guests grow | --max-total-run-memory | 0 (unbounded) | a growth the pool can’t serve before the run’s deadline is denied |
private /tmp | none in the runtime: the filesystem behind $TMPDIR | TMPDIR | the pod’s /tmp | the guest’s write fails (ENOSPC); the runtime is unaffected |
| one run, HTTP egress | per-run budgets, fixed at 16 requests, 4 MiB of request body, 4 MiB of response bytes, 5 redirects and a 10 s timeout per request | none | as stated | the request is answered with an error the guest reads; the run goes on |
| HTTP egress rate | token bucket per module digest | --egress-rate-limit-per-minute, --egress-rate-limit-burst | off | a budget error the guest reads; the run goes on |
The budget of a run is wall-clock time. The epoch deadline interrupts guest
code alone. A guest suspended in a host call, such as a WASI clock or poll,
executes nothing, and a wall-clock timer ends its run at the same deadline
with the same message. The time a guest waits for the host’s HTTP answer in
wasi:http is credited back to both, once for sends that overlap, so a slow
upstream doesn’t spend limits.timeout. The request’s own gRPC deadline stays
the hard cap. Without
one the credit is still bounded: every egress request is cut at the run’s
deadline, and a run stretches to about twice its budget at most.
Creditable time is wasi:http time alone. Crediting arbitrary host time would let a guest
stretch its wall clock through a host import with no such bound.
Compiles and the memory tier
The compile semaphore defaults to one because Wasmtime compiles in parallel across every core it’s given: two compiles at once finish no sooner than one after the other and add a second gigabyte of peak memory. A larger value suits large nodes serving a crowd of small modules, where a compile takes milliseconds and the queue, not the CPU, is the bottleneck. A failed load isn’t cached, and the next request retries. The cache record describes the caches.
Run slots and fairness
The caller (Crossplane’s reconcile workers) bounds concurrency unless the
operator sets --max-concurrent-runs. The flag is off by default because a
run’s memory is capped per run and a semaphore adds head-of-line blocking. It
exists for deployments where the caller’s concurrency isn’t the number to size
for: more than one Crossplane instances or a large worker count sharing one runtime, or
a memory-tight pod where concurrent runs times --module-memory-limit must not
be reachable.
With the flag set, the engine’s FairScheduler (crates/engine/src/concurrency.rs)
queues waiters per module digest and admits them round-robin. A freed slot goes
to the next digest in rotation, first in first out within one digest. One hot
module takes at most its share of the slots, and a request’s wait
scales with the modules queued ahead of it, not the requests. With one
digest waiting the scheduler is a plain FIFO.
limits.concurrency adds a bound per step. StepSlots keeps a semaphore per
module digest, so two Compositions naming the same module share it. A run takes
its step slot before the global one, so a step that has used its share doesn’t
occupy a global slot. A digest’s slot count is set by the first step to use it
and applies until the entry is swept after ten idle minutes.
The run’s budget or the request’s gRPC deadline, whichever comes first, caps each wait. A queue never outgrows what its callers still wait for, and a request that gives up took no slot and isn’t counted as a run. The refusals are fatal results:
waiting for a run slot: deadline exceededwaiting for one of this step's 2 run slots (limits.concurrency): deadline exceeded
A run takes its slot after the module has loaded, around one run, so
guestfn_module_run_duration_seconds measures runs rather than queues.
guestfn_module_runs_in_flight pinned at --max-concurrent-runs means
the queue is the bottleneck.
Run memory pool
--max-total-run-memory bounds the total memory of all running guests, their
linear memories and tables together.
A component has no top-level memory to reserve ahead of the run. Each run
charges the pool as its guest grows, the initial memory included, and releases
everything when its store drops. The pool reflects what runs use, and a small
guest doesn’t wait on a worst-case ceiling it never claims. A growth the pool
can’t serve before the run’s deadline is denied. The guest sees memory.grow
or table.grow fail, as at the per-run ceiling, the runtime logs Denied a memory growth or Denied a table growth and the denial counts in
memory_denials_total{reason="pool"}. The runtime refuses
at startup a pool smaller than --module-memory-limit, since no full-limit run
could ever fit.
The acquisition order is the step slot, the global slot, then memory as the run grows. A run waiting for the pool keeps its run slots, and runs with partial reservations can wait on each other. The deadline of the run bounds each wait and denies the growth when it passes. A cycle lasts no longer than a deadline.
Egress rate
A module called once per XR against one endpoint makes a request per reconcile
per XR. RateLimiters in crates/function/src/egress.rs keeps a token bucket
per module digest, process-wide, consulted after the per-run request count. The
digest, not a host or a Composition, is the key: it’s the unit of the audit
line, idle buckets expire so the map follows the modules in use, and one
module’s traffic can’t exhaust another’s rate. A bucket starts full.
--egress-rate-limit-burst sets its size, and 0 derives
max(1, requests per minute). Over the limit, the guest reads
sandbox.egress: the module's request rate exceeds the egress policy's rateLimit
and http_requests_total{outcome="budget"} counts the request. The check
returns at once, and the module retries on its next reconcile. The ten-minute sweep drops
idle buckets. The operator sets the rate, and a Composition can’t change it.
Sizing
The sizing page has the measurements. The terms are:
- Memory is the resident compiled modules plus
--max-concurrent-compilestimes the peak of compiling the largest module plus concurrent runs times the per-run figure.--max-concurrent-runs, when set, caps the last factor (at--module-memory-limitper run in the worst case), and--max-total-run-memorycaps the sum of what runs claim. - CPU is requests per second times the per-request cost, plus the compiles, one per module version per cache.
- Cold start is the compile CPU of every module over the cores. A volume
under
/tmp/guestfn-cachereplaces compiles with loading the stored artifact, and--warm-modulesmoves either ahead of readiness. - Disk is a module and its artifact per version served, until
--max-cache-sizebounds it.
The dominant per-request cost is the guest’s own initialisation, not the host, so the toolchain choice is the sizing decision.
Readiness and warmth
The runtime reports the gRPC health service on the function port and plain-HTTP
/readyz on --health-address, ready once the caches are open and the
--warm-modules entries are loaded. Ready isn’t warm by default: the first
request for each module on a pod pays a map from a warm volume or a compile from
cold. The volume-backed cache covers restarts, and the compile semaphore keeps a
cold fleet from thrashing. Readiness and warm-up is the
manual page, and the cache record covers what warm-up loads.
Failure containment
A run that traps, exits, times out or exhausts its memory is a fatal result. A panic in the host on the run path becomes a fatal result too, and a load that fails isn’t cached. The process is never the unit of failure for one request, which is the property every bound here protects.
The sandbox’s other grants have bounds in the table. The filesystem behind
$TMPDIR bounds the private /tmp, because WASI pre-opens don’t support a
quota and the runtime adds none. The per-run budgets bound egress, and an
operator can’t configure them. Host directories aren’t mountable, so nothing
else on the pod’s filesystem is a module’s to read.
Observability
The series are documented. Those that govern resources
are guestfn_module_run_duration_seconds{outcome} (timeouts are an
outcome of their own, and a wait for a run slot is outside it),
guestfn_module_runs_in_flight,
guestfn_module_compile_duration_seconds,
guestfn_module_cache_events_total{cache,event},
guestfn_module_cache_bytes{cache} from the sweep, and
guestfn_module_memory_denials_total{reason}. No series has a module,
digest or host label: the set is unbounded.
Alternatives
Fuel. Wasmtime’s instruction counting (a fuel budget per run) would have
bounded CPU rather than wall clock. The project dropped it while wazero was the
fallback engine, because it couldn’t build a feature tied to one WebAssembly
engine. It also changes the generated code, which needs a separate compiled
cache namespace. The epoch deadline, a wall clock that credits
wasi:http time back, remains the run bound.
A response cache for egress. Caching the HTTP responses of a module would cut
the thousand identical requests per sweep that the rate limit now bounds. The
invalidation semantics (TTL, Cache-Control, key correctness across headers)
add more complexity than the benefit repays when modules already run in
milliseconds. The limit refuses instead.
A metric label from the Input’s name. An Input is a fragment embedded in a
Composition, so its metadata.name is unset in practice and, when set, is
neither unique nor informative across the Compositions one runtime handles.
The label’s signal was unreliable.
One FIFO for run slots. The first form of --max-concurrent-runs was one
queue, which put a slow module’s requests ahead of every other module’s. The
per-digest round-robin replaced it.
Reserving the whole memory limit up front. A run reserved its effective limit before starting, which capped parallelism at what a worst case would claim. The pool charges growth as it happens instead.
Open questions
- Should the egress rate limit also key by destination host? A per-host bucket would protect a third party across modules, and needs a bounded key set first. It stays per module digest until then.
- Should warm-up load from a bounded “last served” file on the cache volume? It
would make the warm set a function of history that a fresh volume lacks and an
operator can’t read from the deployment.
--warm-modulescovers cold starts and a persistent volume keeps artifacts; revisit if a real fleet shows the gap.
Three-layer authorization model
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.5 (revision 1.5 applies a
forbidwith an unconstrained action to the scoped default-permit actions without scoping them; the read fence,requireResource, beside the output fence; rewritten in the present tense over the Rust workspace; supersedes the request-delivered-secrets record)
Summary
A capability is granted on the agreement of three parties, and on nothing less, down the trust ladder (Jonasz, 2026-08-19). The module’s manifest is the request. The composition policy and the operator policy, both Cedar, are the grants, and each can narrow what the preceding layer allows and nothing more.
grant(capability) =
manifest REQUESTS it (module author, least trusted: the ask)
∧ composition policy PERMITS it (composition author: narrows this Composition)
∧ operator policy PERMITS it (operator: the ceiling, --sandbox-policy-file)
The capabilities are a private /tmp (usePrivateTmp), HTTP egress to a host,
method and path (grantEgress), an environment variable bound to a step
credential (setEnv and spendCredential), a step credential read whole from
the request (spendCredential) and the repository of a source an XR chose
(pullModule). composeResource fences what a module writes and
requireResource what it asks Crossplane for, both over the response rather
than as capabilities (see “The output fence” and “The read fence”).
Because each decision belongs to a layer, the Input has no sandbox or
policy field. It holds module, limits, config and an optional
compositionPolicy, the composition author’s raw Cedar. limits stay numeric
clamps. Non-secret module settings live in config, which the guest reads
through GetConfig.
Trust safety
Each layer is a separate Cedar PolicySet, and the layers are AND-combined, so
no layer can widen another. A greedy manifest still meets both policies, and a
composition author who writes permit(everything) has merely declined to narrow:
the operator policy still caps. Each layer is evaluated apart from the others.
Defaults per layer
The layers don’t share a default: each matches its trust role.
The operator layer is default-deny. Without --sandbox-policy-file, a module
gets the default sandbox and nothing else.
An absent manifest requests nothing, so a path, http or OCI source without
a manifest runs in the default sandbox. A manifest can refuse earlier and nothing more; it
never makes a run possible. A path or http source can point at a
guestfn.yaml by reference (manifestPath, manifestURL). Such a source is a static source,
fenced like any other, and the manifest read through it makes the same request.
See Module manifest and
Module manifests.
The composition layer has two regimes, by capability:
- Sandbox capabilities (
grantEgress,usePrivateTmp,setEnv, andspendCredentialfor a credential the module reads from its request) are scoped default-permit. A composition policy that’s absent, or has no rule for an action, doesn’t narrow it, and the operator and manifest decide. Once a rule scopes an action, that action becomes default-deny within this layer: the author has opted in to narrowing it. - Source fencing (
pullModule, andspendCredentialfor the source’s pull credential) of afrom-chosen source is default-deny. An XR’s choice of module is refused unless the composition policy permits its repository. A static source, one the Composition specifies itself, isn’t judged by this layer: it’s the composition author’s own choice.
| composition policy state | sandbox capability | from source fence | output fence |
|---|---|---|---|
| absent | permit | deny | permit |
| present, no rule for the action | permit | deny | permit |
present, a permit for it | permit if matched, else deny | permit if matched, else deny | permit if matched, else deny |
present, a forbid for it | forbid wins | forbid wins | forbid wins |
A forbid that leaves its action unconstrained, forbid (principal, action, resource) when { … };, applies to the scoped default-permit actions without
scoping them: where no other rule specifies the action, the layer refuses what the
forbid matches and permits the rest. That holds for the sandbox actions in
the composition layer and for the two response fences in both layers. A
permit with an unconstrained action scopes nothing.
A malformed compositionPolicy is a fatal result at admission, and a
malformed operator policy is a startup or function validate error. The
runtime compiles the composition policy once per distinct text, cached by
content hash.
Environment and step credentials
A module that reads $DATABASE_URL alone declares the binding in its manifest:
requires.env: [{name: DATABASE_URL, fromCredential: {name: db, key: url}}].
The runtime resolves it from the request’s step credentials, and
spendCredential for db must be permitted by both Cedar layers. The module
defines its env contract and never supplies the value. A binding lists the keys it needs
and no others. There’s no bulk import of every key of a credential.
Step credentials arrive in every RunFunctionRequest. Crossplane hands them
all to a native function, and forwarding them all made spendCredential gate
a convenience: a module denied an env binding could still read the key from
its request (issue #122, 2026-10). The runtime edits the request at the wire
level instead, and the module receives:
- the credential each admitted
requires.envbinding reads, whole; - each credential the manifest lists under
requires.credentials, whole: a shared Secret the module picks a key from, admitted byspendCredentialunder both layers like an env binding’s.
A module without a manifest, or whose manifest doesn’t require a credential, sees none. The pull credential is never forwarded, and the runtime refuses a manifest that names it. A required credential that either layer doesn’t permit, or that the step doesn’t include, is a fatal result before the run:
… requires credential "cmdb" (requires.credentials[0]), which the operator policy (--sandbox-policy-file) does not permit
function validate --resolve lists the credentials an admitted step’s module
receives.
The output fence
composeResource (Jonasz, 2026-10-27, #174) fences what a module composes.
After the run, the runtime diffs the response’s desired state against the
request’s and judges every change (an addition, a modification or a removal,
the composite’s included) as Kind::"<group>/<Kind>" in a Group hierarchy,
with context.change, name and target. modify is judged on the entire
resource, compared by value. The composition layer is evaluated first and
whole, then the operator’s. A refusal is a fatal result naming kind, name,
change and layer.
It’s the one action that’s scoped default-permit in the operator layer too.
A module’s output was never gated before the fence, and a default-deny would
have refused every module’s output on upgrade. A runtime with no policy file,
or a layer with no rule for the action, narrows nothing. Once scoped, Cedar’s
usual rule applies, and a forbid alone permits nothing. A context.fields
set that would let a policy permit the ready flag alone is a possible additive
extension no use case has asked for yet.
The read fence
requireResource (Jonasz, 2026-11-05, #208) fences what a module asks
Crossplane for through the response’s requirements. After the run, and
before the output fence, the runtime judges every resource selector in
requirements.resources and the deprecated requirements.extra_resources
as Kind::"<group>/<Kind>" in the same Group hierarchy, with
context.name, labels (a record) and namespace where the selector sets
them. It’s scoped default-permit in both layers for the output fence’s
reason. A refused selector is a fatal result naming kind, match, namespace,
entry and layer, and the ask isn’t relayed. A response with a fatal result
is judged too, since the ask travels whatever the results say. The design
record is Read fence.
Cedar schema
Both policies compile against one schema. The composition policy can use
pullModule, spendCredential, grantEgress, usePrivateTmp, setEnv,
composeResource and requireResource, and the operator policy everything but
pullModule, plus requireSignature, trustSigner and dialAddress. The principal is
Request { namespace, xrKind, composition }. The entities, the contexts and
the evaluation rules are on Cedar policy.
Code shape
crates/function/src/authz.rs is the one file that imports cedar-policy. It
holds CompositionPolicy and OperatorPolicy with a permits_* method per
action, and scopes_action (the composition layer’s opt-in signal, with
scopes_action on the operator’s for the two response fences).
crates/function/src/admission.rs combines them: admit runs the Input’s
checks, admit_requires intersects the manifest’s request with both layers
into Capabilities, admit_compose judges the output fence and
admit_require the read fence, over the selectors
crates/function/src/require.rs reads from the response. crates/function/src/from.rs applies the from
fence. crates/function/src/sandboxenv.rs materializes the env bindings and
checks the required credentials, and crates/function/src/runner.rs drops
the credentials that weren’t granted from the request it forwards. function validate calls the same
functions.
Alternatives
Cedar for limits was rejected: a numeric clamp isn’t an authorization
question. The limits remain Input fields under the runtime’s ceiling flags.
A default-deny output fence in the operator layer would have matched the other capabilities. It lost because it would have broken every existing module on upgrade.
Non-goals
- Letting the manifest or the composition policy widen past the operator ceiling. The AND combination makes it impossible.
- A permissive default for the operator layer or the
fromfence. Both stay default-deny. The output fence is the recorded exception. - Fencing
resultsorcontextwrites (Jonasz, 2026-11-05).resultsare messages.contextis a scratch space the pipeline’s later steps read and the last step’s output drops, and it reaches nothing in the cluster, so a fence would guard nothing.requirementswas here until the read fence (#208).
Trust model
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.13 (revision 1.13 forwards the request and the response as function-sdk-rust’s messages, which keep the fields they don’t know, where the proxy edited raw bytes, 1.12 holds a redirected HTTP download to the default block list, and 1.11 keeps the signature verdict per repository and digest; rewritten in the present tense over the Rust workspace; keyless signatures (#116) and the trusted root over TUF (#183) folded into the body as the design)
Who decides what code runs, what that code can see and reach, and what the runtime guarantees to each of them. The 2026-08-16 review found two ways an earlier model leaked: a step credential could be aimed at a host an XR author chose, and a module could read every credential its step declared. The model below closes both. The operator-facing summary is the manual’s trust model. This record keeps the reasoning.
Parties
- The operator installs the Function, sets its flags (limits, the signature keys and trusted root, the served directory, the runtime’s Docker config) and controls the pod: its volume, network policy and resource limits.
- A Composition author references a module in a pipeline step’s Input
(
module.typeplusoci,httporpath), states its digest, may specify a step credential for the pull, sets thecompositionPolicyand thelimitsof the run, and passesconfig. ThecompositionPolicyis their own Cedar layer: it fences the modules an XR may choose and may narrow sandbox capabilities. They’re trusted with the request their step receives, as the author of a native function’s Composition is. - A composite resource author may, when the Composition says so
(
module.from), choose which module runs by writing a field of their XR. They’re trusted with less. They can pick code within thepullModulepermits of thecompositionPolicybut can’t widen what it may do or spend what it may not. The runtime readscompositionPolicyandlimitsfrom the Input alone. - A module author publishes signed or unsigned artifacts and declares in
the manifest what the module can’t run without (
requires), the step credentials it reads among them. Their code runs in the sandbox with the request less the step credentials it wasn’t granted. A manifest can make a run fail earlier, never widen it. - A signer, for a keyless signature, is the OIDC identity the certificate
names. The operator decides per repository which issuer and identity may
vouch for a module (
trustSignerrules).
The Input’s schema is in the module source schema. Every capability a module gets is the AND of three layers, the manifest, the composition layer and the operator layer, described in the three-layer authorization record; the sandbox’s grants are in the sandbox record.
What pins the code
Each remote module is pinned by a digest stated in the Composition or the XR
field: the manifest digest of an OCI reference (repo[:tag]@sha256:…; a tag
alone is refused) or http.digest. The manifest states its layer’s digest,
and the registry client verifies both. Served files (path) are unpinned by
design: the operator put them on the pod. The caches key on these digests and
the runtime verifies every fetch before it stores or compiles it, so nothing
that runs can change without the Composition (or the XR field it delegated
to) changing.
With --cosign-key, an OCI module with a valid signature runs, and
unsigned ones, http and path sources are refused. Verification is a precondition of
running, checked once per repository and digest per process before the runtime looks in any
cache tier, so a runtime with a key never serves an artifact that a runtime
without one (or with a since-rotated key) left on a shared or persisted
volume.
The signature format
The signature is cosign 3’s: a Sigstore bundle (v0.3) holding a DSSE envelope
around an in-toto statement, pushed as an OCI 1.1 referrer whose subject is
the module’s manifest. The runtime lists the referrers through the
registry’s referrers API, or through the sha256-<hex> index of the
referrers tag schema where the API answers 404 (GHCR, registry:3), over its
own registry client with the pull’s credentials. Because the listings aren’t
pinned, a referrer whose subject isn’t the pinned digest doesn’t count, and the
runtime fetches the bundle with a size bound and verifies it against its
digest.
A module is signed when an envelope signature over the DSSE
pre-authentication encoding verifies and the statement it signs is a cosign
signature (predicateType https://sigstore.dev/cosign/sign/v1) whose
subject is the manifest digest. The runtime reads the statement after
the signature verifies, never before. Other attestations, such as SLSA provenance, never
count, whichever key signed them. cosign 2’s legacy sha256-<hex>.sig
signature isn’t read: a module signed that way alone is unsigned to this
runtime until it’s re-signed with cosign 3.
Key-based and keyless bundles
For a key-based bundle the keys --cosign-key names are the trust root. The
bundle’s verification material (key hint and Rekor entries) isn’t consulted.
A bundle that contains a certificate is keyless (#116). sigstore-verify
takes the signing time from the bundle’s RFC 3161 timestamps and its Rekor
entry’s signed entry timestamp (a source that’s present but fails is fatal,
with no fallback to the clock). It verifies the inclusion proof and
checkpoint, then chains the certificate to a Fulcio authority at that time.
The statement is read after that, never before, under the same rules as a key-based bundle’s. The signer is
then held to the operator’s trustSigner rules, in the policy file that
requires the signature: context.issuer and context.identity over the
repository hierarchy, default-deny, so a trusted root alone admits nothing.
A keyless bundle met by a runtime with no trusted root is refused by name
(both flags) and never fails the check for a key bundle beside it.
The trusted root
The root is a file read at startup (--cosign-trusted-root, the air-gapped
mode) or fetched over TUF from a well-known instance
(--cosign-trust-instance public-good|staging|github, #183) and refreshed
while serving every --cosign-tuf-refresh. The TUF root embedded in the
sigstore-trust-root crate is the trust anchor. The walk (root, timestamp,
snapshot, targets, each signed and expiring) pins trusted_root.json by
length and hashes, and the runtime caches the verified metadata under the
module cache root. --cosign-trusted-root and --cosign-trust-instance
exclude each other.
A pod that can’t fetch starts from that cache, re-verified offline from the embedded TUF root. With no cache it serves, refuses keyless signatures naming the instance and the last failure, and retries once a minute. That’s fail-closed per module, and it never becomes a crash loop that takes key-signed and unsigned modules down with it. A changed root forgets the memo of verified modules, so a signer a rotation dropped is re-verified on the module’s next request, while a failed refresh keeps the last good root. Verification never touches the network. Both root flags are opt-in: the runtime doesn’t open a connection the operator didn’t ask for.
Which repositories must be signed
An operator --sandbox-policy-file makes the rule per repository. A
requireSignature rule demands a signature for the repositories it names,
--cosign-key and the trusted root supply what verifies it, and a required
module the runtime can’t verify is refused (fail-closed). A repository
outside every rule runs unsigned. The runtime warns at startup when a key is
set but the policy requires a signature nowhere, when a trusted root is set
without a trustSigner rule, and when trustSigner rules have no root. The
choice of which repositories must be signed is operator policy, described in
the Cedar policy reference.
Credentials and the compositionPolicy fence
A step credential (module.oci.credentials) is spent on a module the
Composition itself names, or on an XR-chosen module the Composition’s
compositionPolicy explicitly permits. Otherwise a source read from the XR
may not specify one: the XR author would also pick the registry host, and a
registry that sends a Basic challenge receives the secret (the review
demonstrated it). XR-chosen modules are then pulled with the
runtime’s own Docker config (DOCKER_CONFIG, mounted by the operator, its
entries bound to their registry host) or anonymously, and an XR object with
credentials is a fatal result that explains why and points at the policy.
The compositionPolicy is a top-level Input field, never read through
module.from. It fences what an XR-chosen module may be and spend:
module:
type: OCI
from: status.module # the XR names {ref, credentials}
compositionPolicy: |
permit (principal, action == Action::"pullModule",
resource in Repository::"ghcr.io/example-org");
permit (principal, action == Action::"spendCredential", resource == Credential::"registry")
when { context.repository in Repository::"ghcr.io/example-org" };
pullModule: an XR-chosenref(orurlforHTTP) must be permitted for its normalized location (registry/repository,scheme://host/path) over the boundary-correctRepositoryhierarchy. A permitted prefix never admits a sibling namespace or adjacent host (a trailing slash is optional), and a ref or URL with dot segments is refused before matching. Anything else is a fatal result that states the policy and the ref. AcompositionPolicyis required whenevermodule.fromnames an OCI or HTTP source: an unfenced XR author could point the runtime at any host and read what its answer says.spendCredential: the step credentials an XR-chosen object may name, spent on a refpullModuleadmits and on no other. The pull check runs first, so a permitted credential never goes to a host the Composition didn’t admit, andcontext.repositorylets a permit co-locate credential and repository. With no matching permit there is none, and the credential is a fatal result.
A static source isn’t subject to the fence: the Composition named it and is
trusted with it. crates/function/src/from.rs applies the rule, judged by
crates/function/src/authz.rs.
Credentials the module receives
The credential that pulled the module is the host’s. The runtime removes it
from the request before the guest sees it, and refuses a manifest that binds
it to an env variable or requires it whole. Of the step’s other credentials
the guest receives those granted to it and no others: each one its manifest names (a
requires.env binding’s credential, or one it reads whole through
requires.credentials) and both Cedar layers permit (spendCredential: the
composition layer’s scoped default-permit and the operator’s default-deny).
The runtime leaves every other one out of the request it forwards. It
forwards the request as function-sdk-rust’s message, which keeps the fields
it doesn’t know on every message of the function API, so
fields newer than the vendored proto still arrive at the guest. A module with
no manifest, or one that doesn’t require a credential, sees none. A
credential the manifest requires that the step doesn’t declare is a fatal
result before the run, as an env binding’s is.
Declaring a credential for the step doesn’t hand it to every module that
runs there: spendCredential keeps a secret from a module, not
out of its environment alone (issue #122, 2026-10). A granted credential can
leave where egress is granted and nowhere else. Without a grant the module has no
network. With one it contacts the hosts its manifest listed within both
Cedar layers and no others, a grant that’s the policy layers’ alone, so nothing an XR
author writes widens where a credential may go.
The guest’s request and sandbox
The guest receives the whole RunFunctionRequest less every step credential
it wasn’t granted (the pull credential always): observed and desired state,
context, extra resources, config, and the credentials its manifest names
that both Cedar layers permit. It runs in a fresh Wasmtime store with WASI
0.3 and 0.2 and no sockets. It has two ways out: the typed log import and
wasi:http. The host performs wasi:http within an egress grant its
manifest requires and both Cedar layers permit (grantEgress), and refuses it
otherwise. A wall-clock deadline and a memory cap over linear memories and
tables bound the run, and stdout and stderr go to the pod’s log.
The guest has no pre-opened directories and no environment unless its
manifest’s requires asks and the policy layers permit. Then it gets a
private /tmp created for the request and removed after it, and an
environment holding the variables its bindings resolve from step credentials
and nothing of the runtime’s own. The private /tmp is the one directory a module ever gets:
host directories aren’t mountable by design (a module’s inputs come through
the request), so no operator path is readable by a module. The runtime reads
the policy layers from the Input and the operator’s file alone, so an XR
author can’t widen them.
Everything the module produces leaves in the response, which the host
forwards whole, adding meta when the guest omitted it. A trap, exit,
timeout, memory exhaustion, bad ABI or host-side panic on its request is a
fatal result, never a crashed process, so one module can’t take the runtime
down for the Compositions sharing it (the bounds are in the
resource governance record).
Through the module they pick, an XR author can write desired state and
results into their own XR. Any module of that Composition has the same power
over that XR, unless the compositionPolicy or the operator’s policy fences
composeResource (#174). Then each change the module makes to the desired
state (a resource added, modified or removed, the XR’s own status included)
must be permitted by kind, and a refused change is a fatal result: none of
what the module composed is applied. Where a layer fences requireResource
(#208), each resource the module asks Crossplane for through the response’s
requirements must be permitted by kind too, and a refused selector is a
fatal result that Crossplane fetches nothing for. They can’t pick a module
outside the
compositionPolicy’s pullModule permits or one the runtime’s signature
policy refuses, spend a step credential no spendCredential permit names for
that repository, widen the run’s limits or the sandbox, or read another
XR’s request.
Supply chain of the runtime itself
The release image builds in a Rust stage and runs on a digest-pinned
Chainguard glibc-dynamic base, chosen over distroless for scanning clean,
with Renovate bumping the digest. It runs as nonroot, and supplychain.yml
signs and attests it. grype-scan.yml scans the latest release weekly, and
Wasmtime bumps arrive as their own Renovate PRs so a review sees the
sandbox’s own security fixes alone.
Threats considered
| threat | answer |
|---|---|
| tag moved to malicious content | tags alone are refused; a tag next to a digest is decoration |
| registry or CDN serves other bytes | manifest verified against the reference, layer against the manifest, module against the layer digest, twice (registry client, host) |
| tampered cache volume | blobs verified against their name on every read; artifacts validated by Wasmtime; signature checked before any tier |
| XR author aims a credential at their host | refused unless a compositionPolicy spendCredential permit names the credential and a pullModule permit admits the host |
| XR author widens the policy, limits or sandbox through the XR | impossible: compositionPolicy and limits are top-level Input fields, the runtime reads module.from from the XR and nothing else, and the sandbox is the manifest’s ask under both Cedar layers |
| XR author picks unsigned code | --cosign-key or a requireSignature rule refuses it |
| module reads or exfiltrates a step credential | a module sees the step credentials its manifest names and both Cedar layers permit (spendCredential) and no others; the runtime edits every other one, the pull credential always, out of its request before the module runs. No network by default. Where both Cedar layers permit egress (grantEgress) a module may use the hosts, methods and paths its own manifest’s requires.egress.http rules declare and none other. A default list of blocked ranges covers loopback, link-local, private and cluster ranges (dialAddress adds more). The runtime judges each resolved address and dials the checked one, and each request leaves an audit line with the module digest. A signature rule is strongly recommended wherever egress is granted |
| module attacks the host | Wasmtime sandbox; host panics are caught into a fatal result |
| module reads or writes host files | never: host directories aren’t mountable into a module. A module gets at most its private /tmp, a fresh directory per request that’s removed afterward. The filesystem behind $TMPDIR bounds it, and Wasmtime refuses .. escapes inside the pre-open (EPERM) |
| module reads the runtime’s environment | never: the WASI environment is empty, or the manifest’s requires.env bindings resolved from step credentials the request already included and nothing more |
| module starves the runtime | deadline, memory cap, compile slots, bounded tiers |
SSRF through module.from (type: HTTP or OCI) | a compositionPolicy pullModule permit is required for an XR-chosen network source. The runtime fetches from repositories the Composition permitted and from no others; permits match a normalized location over the boundary-correct hierarchy and dot segments are refused, so a prefix can’t be escaped; the runtime sends GET requests and no other method, and follows a redirect of an HTTP download to another host at an address outside the default block list, never to one inside it; restrict the pod’s egress with a NetworkPolicy where internal endpoints matter |
| decompression bomb in a tar layer | extraction bounded at eight times the module size limit |
Alternatives
Forward every step credential. The runtime’s first versions, like a
native function, forwarded every step credential but the pull credential. That made
spendCredential gate a convenience: a module denied an env binding still
read the key from its request. The runtime forwards what the module was
granted and nothing else.
Verify key-based bundles through the keyless verifier. One verification
path would be simpler, but sigstore-verify refuses a public-key bundle
that has neither a transparency log entry nor a timestamp. That’s what
cosign sign --key --tlog-upload=false writes. Key bundles stay on a path
where the configured keys are the whole trust root.
WASM sandbox
- Owner: @jonasz-lasut (Jonasz Małecki)
- Reviewers: function-wasm maintainers
- Status: implemented, revision 1.10 (revision 1.10 adds the 6to4, Teredo, local-use NAT64, benchmarking and
192.0.0.0/24ranges to the block list and bounds a request body; rewritten in the present tense over the Rust workspace; host mounts removed (Jonasz, 2026-08-16); Cedar is the one authority that enables a capability (Jonasz, 2026-08-19); the ask is stated in the module’s manifest)
How the sandbox grants a module some filesystem, network or environment access without giving up what makes it safe to run other people’s modules. The operator-facing reference is HTTP egress and Cedar policy. This record gives the reasoning.
Background
A module runs in a fresh Wasmtime store per request. By default it has the
clock and entropy, stderr and stdout inherited from the pod, the typed log
import, an epoch deadline (--module-timeout) and a memory cap
(--module-memory-limit). It has nothing else: the guest sees an empty environment, and WASI offers it neither a directory nor a socket. Everything a module needs arrives in the
RunFunctionRequest (observed and desired state, context, credentials,
required resources) and everything it produces leaves in the response. That
covers composition logic in full. It doesn’t cover a call to an external
system or a secret read from the environment. The grants below are for those.
Principles
- Capabilities are explicit grants. Nothing is ambient, and the operator denies by default.
- The policy layers are the Composition’s and the operator’s, never the
composite resource’s.
compositionPolicyis read from the Input alone, not throughmodule.from: an XR author who can pick a module must not be able to widen what modules may do. - The host enforces and the guest asks. Paths and network requests are checked on the host against the grant; the module is never trusted with policy.
- Grants are bounded in bytes, requests and time. The metrics count their use and each log line has the module’s digest.
- The ABI is language-agnostic. A capability is WASI itself or a host import with a documented contract, so no guest language is second-class.
- A module may request a capability, never take it. Its manifest lists the
egress rules, the private
/tmpand the env bindings it can’t run without (module manifest); a capability is granted where both policy layers permit it, and nowhere else (three-layer authorization). The manifest can make a run fail earlier, never succeed.
Design
The ask is stated in the module’s manifest, not in the Input:
# guestfn.yaml
requires:
filesystem:
privateTmp: true # a private, empty, writable /tmp for the duration of the request; nothing else is mountable
egress:
http: # egress through the host, HTTP(S) only
- host: api.example.com # exact host, or hostPattern: "*.internal.example.com" - exactly one
methods: [GET, POST] # at least one; nothing is admitted implicitly
pathPrefix: /v1/ # optional
env: # secret env: bindings to step credentials; non-secret configuration is the Input's config
- name: DATABASE_URL
fromCredential: {name: db, key: url}
The manifest loader (crates/function/src/manifest.rs, egress_rules.rs,
sandboxenv.rs) checks these formats. A rule has one of host and hostPattern, host
names are bare, path prefixes are normalized and binding names are
identifiers.
The operator’s Cedar --sandbox-policy-file is the one authority that enables
a capability: usePrivateTmp for the private /tmp, setEnv (with
spendCredential per binding) for the environment, grantEgress for egress
(also the host allowlist) and dialAddress for the CIDR rules. It’s evaluated
default-deny, so with no policy file every requires entry is refused and the
module gets the default sandbox alone, which is all most modules need
(Jonasz, 2026-08-19). The Input’s compositionPolicy may narrow any of
those actions (scoped default-permit: it narrows the actions it writes
rules for and no others). admission::admit_requires decides between load and run, and the
run gets its sandbox or a fatal result such as module … requires a private /tmp (requires.filesystem.privateTmp), but the runtime has no --sandbox-policy-file, which is required to grant sandbox capabilities.
At startup the runtime exits on a --sandbox-policy-file that doesn’t parse
(a malformed IP rule included). It also exits on an unwritable $TMPDIR when
the policy can grant a private /tmp. Both mistakes would otherwise fail
every request that hit them.
Mechanics
Filesystem
privateTmp is a per-run directory under the host’s temp dir ($TMPDIR),
named function-wasm-private-tmp-* and created before the store
(crates/engine-wasm/src/sandbox.rs). It’s pre-opened read/write at /tmp,
and removed when the value of the run drops, on every path out (success, trap,
exit, deadline, host error); a removal failure is logged, never a result. It’s
the one directory a guest is ever given, so a module can’t read an
operator-declared host path. The ABI is unchanged:
guests use their language’s file APIs, and their temp directory already
defaults to /tmp on WASI. The cost on the request path
is one mkdir and one removal. docs/abi-v2.md states the guest-visible
contract.
The directory has no byte quota of its own. The filesystem behind
$TMPDIR alone limits it. Put a tmpfs emptyDir with a sizeLimit there to cap a
request’s writes: a full tmpfs fails the guest’s write, not the runtime
(runtime flags).
Network
A module can’t open a socket. It asks through wasi:http (0.3 client.send
and 0.2 outgoing-handler), and crates/engine-wasm/src/wasihttp.rs bridges both
onto one HttpRequester grant that crates/function/src/egress.rs
provides. The policy stays in the runtime, and every guest language
with a wasi:http client has egress. The host:
- applies the grant on the first request and on every redirect hop: host or pattern, method, and a normalized path prefix (dot segments are refused);
- resolves DNS itself and judges every address a name resolves to against the
block list (
DEFAULT_BLOCKED_CIDRS: loopback, link-local, RFC 1918, CGNAT, ULA, the prefixes that embed an IPv4 address in an IPv6 one (IPv4-compatible, both NAT64 prefixes, 6to4, Teredo), unspecified, multicast, benchmarking,192.0.0.0/24, reserved); the operator’sdialAddressrules punch holes or add blocks, and an explicit block takes precedence; - dials the address it checked without re-resolving or using a proxy, and handles TLS itself;
- enforces fixed per-run budgets (
timeout10 s, 16 requests, 4 MiB of request body, 4 MiB of response, 5 redirects) and the process-wide rate limit (--egress-rate-limit-per-minute,--egress-rate-limit-burst); a request is also cut at the run’s remaining deadline; - counts
guestfn_module_http_requests_total{outcome}and writes one log line per request (method, host, path without query, status or reason, bytes and duration, never headers or body).
A failure returns to the guest as internal-error with the refusal string,
never as a trap. Raw sockets stay out: they would move TLS and address policy
into the guest, where the host can’t see them.
Environment
The manifest’s requires.env bindings ({name, fromCredential: {name, key}})
become the run’s WASI environment (sandboxenv::materialize, applied in
sandbox.rs), resolved against the request’s own credentials. The runtime’s
environment is never inherited, so without a granted binding the guest’s
environ is empty. Each binding needs a setEnv and a spendCredential
permit in both Cedar layers. Literal values aren’t allowed: non-secret
configuration is the Input’s config, read through GetConfig. The pull
credential (module.oci.credentials) is refused as a source, since a module
must never see the secret that fetched it. The same rule keeps it out of
requires.credentials.
Threat model
With egress granted, a malicious or careless module can leak what it
sees in the request, step credentials included. The destination is any host
the grant allows. The
host allowlist, the block list and the per-request audit line are required
parts of the grant for that reason, and --cosign-key is recommended wherever
egress is granted. The private /tmp is per request, empty at the start and
removed at the end: one module can’t leave state for the next or read
another’s. Environment values come from step credentials the step
already receives, and from nothing else. A binding doesn’t widen what the request included.
The per-request deadline and memory cap apply under every grant. The
sandbox protects the runtime and the operator’s boundaries. It doesn’t protect
the data the Composition passes to the module.
Alternatives
Host mounts. A Composition could map an operator-declared host directory
into a module, without write access. The project built it, then removed it (Jonasz, 2026-08-16): a
module’s inputs come through the request, so mapping part of the pod’s
filesystem into a module is a boundary the runtime doesn’t offer. Data a
module needs (templates, CA bundles) travels through config, the context or
a required resource.
Extism’s http_request. Evaluated on 2026-08-16 with probes against
extism/go-sdk v1.7.1. Its allowed_hosts is a hostname glob checked once
before the request, on a hard-coded http.DefaultClient: it ignores the
method, the path and the resolved addresses (it dials a name that resolves to
loopback). It follows redirects to other hosts and honours HTTP_PROXY. A
refusal fails the guest call. The host function can’t be replaced without forking
the SDK, so it couldn’t meet the requirements.
A custom host import for HTTP. Under ABI v1 the guest called a JSON
wasmfn.http import. wasi:http superseded it, which guests’ own
toolchains already speak, with the same host policy in front of it (ABI v1 was
removed in 1.0.0, docs/abi-v2.md).
Enabling capabilities by flag. Per-capability --enable-sandbox-* flags
were replaced by the Cedar policy as the one authority (Jonasz, 2026-08-19,
Cedar policy).
The ask in the Input. The Input once had a sandbox block. The
manifest’s requires replaced it. A module states what it can’t run without,
and the Input’s compositionPolicy narrows it and never widens it
(three-layer authorization).
Open questions
- Should the audit line also be a structured
Resulton the response, visible incrossplane render --include-function-results, as well as a log line? - Should the per-request budgets be lowerable per Input, the way
limitsnarrows the run’s timeout and memory? Today they’re fixed defaults (egress.rs), not a policy file or an Input field. The run’slimits.timeoutstill bounds every request.