hostfunc

package
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 11, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package hostfunc provides host function implementations for sandboxed WASM code.

Host functions are Go functions that can be called from within sandboxed code, enabling controlled access to external resources like HTTP, filesystem, and key-value storage.

Overview

Sandboxed code has no implicit access to system resources. Each capability must be explicitly enabled via a Registry and appropriate configuration.

Registry

The Registry manages available host functions. Register custom functions or use the built-in helpers:

registry := hostfunc.NewRegistry()
registry.Register("my_func", func(ctx context.Context, args map[string]any) (any, error) {
    return "result", nil
})

Built-in Capabilities

HTTP: Controlled network access via HTTP and HTTPConfig.

http := hostfunc.NewHTTP(hostfunc.HTTPConfig{
    AllowedHosts: []string{"api.example.com"},
})
registry.Register("http_request", http.Request)

Filesystem: Mount-based access via FS, Mount, and MountMode.

fs := hostfunc.NewFS([]hostfunc.Mount{
    {VirtualPath: "/data", HostPath: "./input", Mode: hostfunc.MountReadOnly},
})
registry.Register("fs_read", fs.Read)

Key-Value Store: In-memory storage via KV and KVConfig.

kv := hostfunc.NewKV(hostfunc.DefaultKVConfig())
registry.Register("kv_get", kv.Get)
registry.Register("kv_set", kv.Set)

Security Model

All host functions follow the principle of least privilege:

  • HTTP requests are limited to explicitly allowed hosts
  • Filesystem access is restricted to mounted paths with specific permissions
  • All operations have configurable size limits to prevent resource exhaustion

See the executor package for higher-level APIs that configure these capabilities automatically.

Index

Constants

View Source
const (
	DefaultMaxFileSize   = 10 * 1024 * 1024 // 10MB max file read
	DefaultMaxWriteSize  = 10 * 1024 * 1024 // 10MB max file write
	DefaultMaxPathLength = 4096             // 4KB max path
)
View Source
const (
	DefaultMaxURLLength   = 8192             // Maximum URL length in bytes
	DefaultMaxBodySize    = 1 << 20          // Maximum response body size (1MB)
	DefaultRequestTimeout = 30 * time.Second // Request timeout
)

Default limits for HTTP requests.

View Source
const (
	DefaultMaxKVKeySize    = 256              // Maximum key size in bytes
	DefaultMaxKVValueSize  = 64 * 1024        // Maximum value size (64KB)
	DefaultMaxKVEntries    = 1000             // Maximum number of entries
	DefaultMaxKVTotalBytes = 10 * 1024 * 1024 // Maximum total storage (10MB)
)

Default limits for key-value store.

Variables

This section is empty.

Functions

This section is empty.

Types

type FS

type FS struct {
	// contains filtered or unexported fields
}

FS provides filesystem operations with explicit mount points.

func NewFS

func NewFS(mounts []Mount, opts ...FSOption) *FS

NewFS creates a new filesystem handler with the given mount points.

func (*FS) Exists

func (f *FS) Exists(ctx context.Context, args map[string]any) (any, error)

Exists checks if a path exists.

func (*FS) List

func (f *FS) List(ctx context.Context, args map[string]any) (any, error)

List returns the contents of a directory.

func (*FS) Mkdir

func (f *FS) Mkdir(ctx context.Context, args map[string]any) (any, error)

Mkdir creates a directory.

func (*FS) Read

func (f *FS) Read(ctx context.Context, args map[string]any) (any, error)

Read returns the contents of a file.

func (*FS) Remove

func (f *FS) Remove(ctx context.Context, args map[string]any) (any, error)

Remove deletes a file or empty directory.

func (*FS) Stat

func (f *FS) Stat(ctx context.Context, args map[string]any) (any, error)

Stat returns information about a file or directory.

func (*FS) Write

func (f *FS) Write(ctx context.Context, args map[string]any) (any, error)

Write writes content to a file.

type FSEntry

type FSEntry struct {
	Name  string `json:"name"`
	IsDir bool   `json:"is_dir"`
	Size  int64  `json:"size"`
}

type FSExistsRequest

type FSExistsRequest struct {
	Path string `json:"path"`
}

type FSListRequest

type FSListRequest struct {
	Path string `json:"path"`
}

type FSMkdirRequest

type FSMkdirRequest struct {
	Path string `json:"path"`
}

type FSOption

type FSOption func(*FS)

func WithMaxFileSize

func WithMaxFileSize(size int64) FSOption

func WithMaxPathLength

func WithMaxPathLength(length int) FSOption

func WithMaxWriteSize

func WithMaxWriteSize(size int64) FSOption

type FSReadRequest

type FSReadRequest struct {
	Path string `json:"path"`
}

type FSRemoveRequest

type FSRemoveRequest struct {
	Path string `json:"path"`
}

type FSStatRequest

type FSStatRequest struct {
	Path string `json:"path"`
}

type FSStatResponse

type FSStatResponse struct {
	Name    string `json:"name"`
	Size    int64  `json:"size"`
	IsDir   bool   `json:"is_dir"`
	ModTime int64  `json:"mod_time"`
}

type FSWriteRequest

type FSWriteRequest struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

type Func

type Func func(ctx context.Context, args map[string]any) (any, error)

Func is the signature for host functions callable from sandboxed code. Functions receive a context and a map of arguments, returning a result or error.

func NewHTTPGet

func NewHTTPGet(cfg HTTPConfig) Func

NewHTTPGet returns a host function for GET-only requests.

func NewPkgInstaller

func NewPkgInstaller(cfg PkgConfig) Func

NewPkgInstaller returns a host function for installing Python packages via pip. Args: name (required), version (optional).

type HTTP

type HTTP struct {
	// contains filtered or unexported fields
}

HTTP provides controlled HTTP request capabilities for sandboxed code.

func NewHTTP

func NewHTTP(cfg HTTPConfig) *HTTP

NewHTTP creates an HTTP handler with the given configuration. Requests are only allowed to hosts listed in cfg.AllowedHosts.

func (*HTTP) Request

func (h *HTTP) Request(ctx context.Context, args map[string]any) (any, error)

Request performs an HTTP request. Args: method, url, body (optional), headers (optional). Returns a map with status, body, and headers.

type HTTPConfig

type HTTPConfig struct {
	AllowedHosts   []string
	MaxBodySize    int64
	MaxURLLength   int
	RequestTimeout time.Duration
}

HTTPConfig configures HTTP request handling.

type HTTPGetRequest

type HTTPGetRequest struct {
	URL string `json:"url"`
}

type HTTPResponse

type HTTPResponse struct {
	Status int    `json:"status"`
	Body   string `json:"body"`
}

type KV

type KV struct {
	// contains filtered or unexported fields
}

KV provides an in-memory key-value store for sandboxed code. Values are JSON-serializable and subject to configurable size limits.

func NewKV

func NewKV(cfg KVConfig) *KV

NewKV creates a key-value store with the given configuration.

func (*KV) Delete

func (k *KV) Delete(ctx context.Context, args map[string]any) (any, error)

Delete removes a key. Args: key.

func (*KV) Get

func (k *KV) Get(ctx context.Context, args map[string]any) (any, error)

Get retrieves a value by key. Args: key, default (optional).

func (*KV) Keys

func (k *KV) Keys(ctx context.Context, args map[string]any) (any, error)

Keys returns all keys in the store.

func (*KV) Set

func (k *KV) Set(ctx context.Context, args map[string]any) (any, error)

Set stores a value. Args: key, value.

type KVConfig

type KVConfig struct {
	MaxKeySize    int   // Maximum key size in bytes
	MaxValueSize  int   // Maximum value size in bytes
	MaxEntries    int   // Maximum number of entries
	MaxTotalBytes int64 // Maximum total storage in bytes
}

KVConfig configures key-value store limits.

func DefaultKVConfig

func DefaultKVConfig() KVConfig

DefaultKVConfig returns the default KV configuration.

type KVDeleteRequest

type KVDeleteRequest struct {
	Key string `json:"key"`
}

type KVGetRequest

type KVGetRequest struct {
	Key string `json:"key"`
}

type KVSetRequest

type KVSetRequest struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type Mount

type Mount struct {
	VirtualPath string    // Path as seen by sandboxed code (e.g., "/data")
	HostPath    string    // Actual path on host filesystem
	Mode        MountMode // Permission level
}

Mount represents a virtual path mapped to a host path with specific permissions.

type MountMode

type MountMode int

MountMode defines the permission level for a mount point.

const (
	// MountReadOnly allows only read operations.
	MountReadOnly MountMode = iota
	// MountReadWrite allows read and write operations to existing files/dirs.
	MountReadWrite
	// MountReadWriteCreate allows read, write, and create operations.
	MountReadWriteCreate
)

type PkgConfig

type PkgConfig struct {
	PackageDir      string   // Directory to install packages into
	AllowedPackages []string // If set, only these packages can be installed
	Enabled         bool     // Whether package installation is enabled
}

PkgConfig configures the package installer.

func DefaultPkgConfig

func DefaultPkgConfig() PkgConfig

DefaultPkgConfig returns the default package installer configuration.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds registered host functions that can be called from sandboxed code.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty host function registry.

func (*Registry) All

func (r *Registry) All() map[string]Func

All returns a copy of all registered functions.

func (*Registry) Get

func (r *Registry) Get(name string) (Func, bool)

Get retrieves a host function by name.

func (*Registry) List

func (r *Registry) List() []string

List returns the names of all registered functions.

func (*Registry) Register

func (r *Registry) Register(name string, fn Func)

Register adds a host function to the registry. If a function with the same name exists, it is replaced.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL